How do I change the Entry value to int in tkinter? [duplicate] - python

This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 2 years ago.
I want to make a calculator that adds 10 to the number using tkinter.
But I had to get the entry price in int format, so I used get method.
I keep getting the following error message. What's the problem?
from tkinter import *
window=Tk()
a=Entry(window)
a.pack()
b=a.get()
c=int(b)
result2=Label(window,text="")
result2.pack()
def Button_Press():
global c
result=c+10
result2.config(text=result)
button=Button(window,command=Button_Press())
button=pack()
window.mainloop()
Here's the error text.
c=int(b)
ValueError: invalid literal for int() with base 10: ''

ValueError: invalid literal for int() with base 10: ''
Has show you that the c is ''(a string which length is zero).The code seems to be int('').That's why it will raise exception.
Your code could be:
from tkinter import *
window = Tk()
a = Entry(window)
a.insert("end", "0") # just insert a str "0"
a.pack()
b = a.get()
c=int(b)
print(c)
result2 = Label(window, text="")
result2.pack()
def Button_Press():
result = c + 10
result2.config(text=result)
button = Button(window, command=Button_Press) # there is no "()"
button.pack() # not button = pack()
window.mainloop()

Related

Validation python, Using GUI

I am attempting to validate the text box field so that the user can only insert integers, although i have used a while loop to attempt and cannot figure it out I keep getting errors. Please help.
from tkinter import *
import tkinter as tk
from tkinter.tix import *
# setup the UI
root = Tk()
# Give the UI a title
root.title("Distance converter Miles to Kilometers")
# set window geometry
root.geometry("480x130")
# setup the buttons
valRadio = tk.IntVar()
myText=tk.StringVar()
e1 =tk.IntVar()
def calculate(*arg):
while True:
try:
if valRadio.get() == 1:
# get the miles ( Calculation )
res = round(float(e1.get()) / 1.6093,2)
# set the result text
myText.set( "Your input converts to " + str(res) + " Miles")
break
if valRadio.get() == 2:
# get the kilometeres
res = round(float(e1.get()) * 1.6093,2)
# set the result text
myText.set( "Your input converts to " + str(res) + " Kilometers")
break
if ValueError:
myText.set ("Please check selections, only Integers are allowed")
break
else:
# print error message
res = round(float(e1.get()) / 1.6093,2)
myText.set ("Please check selections, a field cannot be empty")
break
except ValueError:
myText.set ("Please check selections, a field cannot be empty")
break
# Set the label for Instructions and how to use the calculator
instructions = Label(root, text="""Hover me:""")
instructions.grid(row=0, column=1)
# set the label to determine the distance field
conversion = tk.Label( text=" Value to be converted :" )
conversion.grid(row=1,column = 0,)
# set the entry box to enable the user to input their distance
tk.Entry(textvariable = e1).grid(row=1, column=1)
#set the label to determine the result of the program and output the users results below it
tk.Label(text = "Result:").grid(row=5,column = 0)
result = tk.Label(text="(result)", textvariable=myText)
result.grid(row=5,column=1)
# the radio button control for Miles
r1 = tk.Radiobutton(text="Miles",
variable=valRadio, value=1).grid(row=3, column=0)
# the radio button control for Kilometers
r2 = tk.Radiobutton(text="Kilometers",
variable=valRadio, value=2).grid(row=3, column=2)
# enable a calculate button and decide what it will do as well as wher on the grid it belongs
calculate_button = tk.Button(text="Calculate \n (Enter)", command=calculate)
calculate_button.grid(row=6, column=2)
# deploy the UI
root.mainloop()
I have attempted to use the While loop inside the code although I can only get it to where if the user inputs text and doesn't select a radio button the error will display but I would like to have it where the text box in general will not allow anything but integers and if it receives string print the error as it does if the radio buttons aren't selected.
define validation type and validatecommand. validate = key makes with every key input it runs validatecommand. It only types if that function returns true which is 'validate' function in this case.
vcmd = (root.register(validate), '%P')
tk.Entry(textvariable = e1,validate="key", validatecommand=vcmd).grid(row=1, column=1)
this is the validation function
def validate(input):
if not input:
return True
elif re.fullmatch(r'[0-9]*',input):
return True
myText.set("Please check selections, only Integers are allowed")
return False
it return true only when its full of numbers([0-9]* is an regular expression which defines all numbers) or empty. If it contains any letter it return False any it denied this way.
Also do not forget to imports
import re

tkinter, < not supported between instances of 'IntVar' and 'int' [duplicate]

This question already has answers here:
'>' not supported between instances of 'IntVar' and 'IntVar'
(2 answers)
Closed 7 months ago.
In python using tkinter. I'm trying to let a user enter a number into an entry box, the number they enter will be the number a loop starts on. An error appears saying: TypeError: '<' not supported between instances of 'IntVar' and 'int'.
root = tk.Tk()
x = tk.IntVar(value=1)
EnterNumber = tk.Label(root, text='Starting server:')
EnterNumber.config(font=('helvetica', 10))
canvas.create_window(100, 680, window=EnterNumber)
Message = tk.Entry(root, textvariable=x)
canvas.create_window(232, 680, height=40, width=50, window=Message)
def Typing():
time.sleep(5)
global x
while x < 212 and not keyboard.is_pressed("q"): #error is here
pyautogui.moveTo(Search)
click()
X = str(x)
s = "smalltribes"
S = str(s)
U = " "
T = S+X+U
pyautogui.write(T)
time.sleep(1)
x += 1
Not all of the code is included just what I thought is needed.
You need to use x.get() wherever you are trying to compare the value of x to something. That is how you get the value that is stored in a tkinter custom variable.

Why does everythin sleeps for 0.5s when I use time.sleep(0.5) instead of only 1 function? [duplicate]

This question already has answers here:
How can I schedule updates (f/e, to update a clock) in tkinter?
(8 answers)
Closed 1 year ago.
I am making a responce bot in python with tkinter. For that when user inputs something I will give answer.
I have not yet completed it. I wanted that the bot should answer after some-time so it looks very nice.
My code:-
import tkinter
from tkinter import Message, messagebox
from tkinter import font
from tkinter.constants import CENTER, LEFT, RIGHT, BOTTOM, TOP
from tkinter import scrolledtext
from typing import Sized
import time
window = tkinter.Tk()
window.geometry("370x500")
window.configure(bg="orange")
#variables
running = True
verdana_12 = ('Verdana', '12')
verdana_10 = ('Verdana', '10')
verdana_9 = ('Verdana', '9')
msg=tkinter.StringVar()
#messages
greetings = ["hi", "hello", "hey", "what's up!"]
questions = [
' 1. What is python?',
' 2. Where to ask questions if I get stuck?',
' 3. How can I get example questions and quizes related to python?'
]
#items inb gui
info_text = tkinter.Label(window, text="Chat", bg="orange", font=verdana_12)
info_text.pack(padx=20, pady=5)
text_1 = tkinter.Label(window, text="Type your message: ", font=verdana_9, bg="orange")
text_1.place(x=0, y=476)
input_area = tkinter.Entry(window, justify=LEFT, textvariable=msg, font=verdana_12, width=16)
input_area.focus_force()
input_area.place(x=135, y=476)
chat_area = scrolledtext.ScrolledText(window)
chat_area.pack(padx=20, pady=5)
chat_area.config(state = "disabled")
#define message
message = f"You: {input_area.get()}\n"
#functions
#def afterwards():
# mine_msg = message.lower().strip().split()[1]
# if 1 == mine_msg:
# reply("Bot: Python is an interpreted high-level general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant indentation. More info at https://en.wikipedia.org/wiki/Python_(programming_language)")
#
# elif 2 == mine_msg:
# reply("Bot: If you get stuck in python programming, go to stackoverflow.com where you can ask questions related to any programming language!")
#
# elif 3 == mine_msg:
# reply("Bot: You can get quizes related to python in w3schools.org and example questions in w3resource.org.")
def reply(reply_msg):
str(reply_msg)
the_reply = f"{reply_msg}\n" #input_area = where person types.
chat_area.config(state='normal')
chat_area.insert(tkinter.INSERT, the_reply)
chat_area.yview('end')
chat_area.config(state='disabled')
input_area.delete(0, 'end')
def check_msg():
global message
print('Message =', message.strip())
try:
mine_msg = message.lower().strip().split()[1]
if greetings[0] == mine_msg or greetings[1] == mine_msg or greetings[2] == mine_msg or greetings[3] == mine_msg:
reply("Bot: Hello, here's how I can help you")
for i in questions:
reply(i)
#afterwards()
else:
reply("Bot: Couldn't understand your message, please type 'hi', 'hello', 'hey' or 'what's up!' to get responce.")
except IndexError:
pass
def write():
global message
if len(input_area.get().split()) > 0:
message = f"You: {input_area.get()}\n" #input_area = where person types.
chat_area.config(state='normal')
chat_area.insert(tkinter.INSERT, message)
chat_area.yview('end')
chat_area.config(state='disabled')
input_area.delete(0, 'end')
check_msg()
else:
reply('Please type something.')
def print_it():
message = f"You: {input_area.get()}"
print(message)
#button_send
send_button = tkinter.Button(window, text="Send", command=write, font=verdana_10, bg="gray", fg="white", width=26, height=1)
send_button.pack(padx=20, pady=5)
window.mainloop()
It freezes everything for 0.5 instead I want it to freeze only the write() function. Any help please.
Thank you!
One way to achieve this would be to use the .after method from tkinter to delay the message from being replied to for a period of time.
i = "My Message"
window.after(1000,lambda i=i: reply(i))
This would call the reply function with the message "My Message" after 1000ms or 1 second.

validation of tkinter entry widget [duplicate]

This question already has answers here:
Interactively validating Entry widget content in tkinter
(10 answers)
Closed 3 years ago.
I have an entry field in my tkinter GUI app. entry should only accept numbers including decimal points. I used a function to validate the entry. The problem is, it is not accepting decimal point(.) if there is a digit in front of it. (example 25.3 wont accept). if there is a point in the beginning, it is not accepting any number after that. Could anyone help me with this problem. and any suggestion to limit the maximum value in the entry field to 1000?
import tkinter as tk
def acceptNumber(inp):
if inp.isdigit():
return True
elif inp is "":
return True
elif inp is ".":
return True
else:
return False
win = tk.Tk()
reg = win.register(acceptNumber)
entryHere =tk.Entry(win)
entryHere.place(x=400, y=200)
entryHere.config(validate="key", validatecommand =(reg, '%P'))
win.mainloop()
This accepts valid decimal numbers not greater than 1000:
def acceptNumber(inp):
try:
return True if inp == '' else float(inp) <= 1000
except:
return False
>>> s='1234'
>>> s.isdigit()
True
>>> sdot = '1234.'
>>> sdot.isdigit()
False
Isn't this your problem. isdigit() means digits only.

Limit user input to numbers? Tkinter-Python [duplicate]

This question already has answers here:
Interactively validating Entry widget content in tkinter
(10 answers)
Closed 8 years ago.
I am trying to make a basic calculator in python tkinter. I made an entry box that user types his first number into. But then, what if someone enters in something other than numbers, but text? My question is, how to make that you can put only number to entry box, or how it can ignore normal letters.
By the way, my half-done code is here:
from tkinter import *
okno = Tk()
okno.title("Kalkulačka")
okno.geometry("400x500")
firstLabel = Label(text="Vaše první číslo").place(x=25, y=25)
firstInput = Entry(text="Vaše první číslo").place(x=130, y=25, width=140)
buttonplus = Button(text="+").place(x=130, y=75)
buttonminus = Button(text="-").place(x=165, y=75)
buttonkrat = Button(text="・").place(x=197, y=75)
buttondeleno = Button(text=":").place(x=237, y=75)
What I would do personally is run every user input through an integer verifying function before accepting it as input. Something simple like this:
def is_int(x):
try:
x = int(x)
return True
except:
return False

Categories