Getting Tkinter.entry Input Into If/else Statements
Here is my current code, which I have changed multiple times using different answers of different answered questions on here. The problem is I am trying to find a way to get the co
Solution 1:
You can convert string to lower case and compare only with "screen"
if entry.get().strip().lower() == "screen":
I use strip()
to remove spaces at the both ends of string because sometimes user can enter extra spaces ie. " screen "
Or you can use in
if entry.get().strip() in ("Screen", "screen", "Monitor", "monitor"):
if entry.get().strip().lower() in ("screen", "monitor"):
because it is shorter then
if entry.get().strip() == "Screen"or entry.get().strip() == "screen"or entry.get().strip() == "Monitor"or entry.get().strip() == "monitor":
if entry.get().strip().lower() == "screen"or entry.get().strip().lower() == "monitor":
You can also use strip().lower()
before if/else
answer = entry.get().strip().lower()
if answer in ("screen", "monitor"):
# ...elif answer in ("mouse", "trackball"):
# ...elif answer == "keyboard":
# ...
Working example
import tkinter as tk
# --- functions ---# `bind` sends `event` to function so it has to receive it# `command=` doesn't sends `event` so it need some default value - ie. Nonedefon_button(event=None):
answer = entry.get().strip().lower()
if answer in ("screen", "monitor"):
# change text in existing label
label['text'] = "Your {} is dirty. I can't see you.".format(answer)
elif answer in ("mouse", "trackball"):
label['text'] = "Your {} is too slow for me".format(answer)
else:
label['text'] = "{0}? What is {0}?".format(answer)
# --- main ---
root = tk.Tk()
root.geometry("300x300")
root.title("Try code")
entry = tk.Entry(root)
entry.pack()
# run function when in `entry` you press `ENTER` on keyboard
entry.bind('<Return>', on_button)
button = tk.Button(root, text="Enter", command=on_button)
button.pack()
label = tk.Label(root)
label.pack()
# activate `entry` so you don't have to click in `entry` to start typing
entry.focus()
root.mainloop()
Solution 2:
Your Boolean expression in your if statement was not right.You have to explicitly tell Python what exactly you want to do:
import tkinter
root = tkinter.Tk()
root.geometry("300x300")
root.title("Try code")
entry = tkinter.Entry(root)
entry.pack()
print(entry.get())
def on_button():
if entry.get() == "Screen"or entry.get() == "screen": #corrected
slabel = tkinter.Label(root, text="Screen was entered")
slabel.pack()
else:
tlabel = tkinter.Label(root, text="")
tlabel.pack()
button = tkinter.Button(root, text="Enter", command=on_button)
button.pack()
root.mainloop()
And now it works:
Post a Comment for "Getting Tkinter.entry Input Into If/else Statements"