将tkinter.Entry输入到if / else语句中

时间:2016-12-11 12:11:40

标签: python python-3.x tkinter

这是我目前的代码,我在这里使用不同答案问题的不同答案多次更改。问题是我试图通过tkinter.Entry()根据用户输入找到一种方法来让代码输出不同的答案。

例如,如果用户输入“屏幕”,则代码将提供有关屏幕的信息。如果用户输入“Python”,则代码将打印与python编程语言有关的内容。

我能够获取代码来打印用户通过.get()函数点击按钮时输入的内容,但是这样它就不会与if / else语句通信。

cordova run browser

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

你的if语句中的布尔表达式不正确。你必须明确地告诉Python你想要做什么:

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()

现在它起作用了:

enter image description here

答案 1 :(得分:1)

您可以将字符串转换为小写字母,并仅与"screen"

进行比较
 if entry.get().strip().lower() == "screen":

我使用strip()删除字符串两端的空格,因为有时用户可以输入额外的空格,即。 " screen "

或者您可以使用in

 if entry.get().strip() in ("Screen", "screen", "Monitor", "monitor"):

 if entry.get().strip().lower() in ("screen", "monitor"):

因为它比

 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":

您也可以在strip().lower()

之前使用if/else
 answer = entry.get().strip().lower()

 if answer in ("screen", "monitor"):
     # ...
 elif answer in ("mouse", "trackball"):
     # ...
 elif answer == "keyboard":
     # ...

工作示例

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. None
def on_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()