您可以创建按钮来运行代码,该代码将从var.get() 或E.get() 获取文本并执行某些操作
E = Entry(top, text='var', textvariable=var, bd=5)
E.pack()
B = Button(top, text='OK', command=faultCodes)
B.pack()
def faultCodes():
entry_text = var.get()
if entry_text == "500" or entry_text == "514":
print("Follow fault code 9621F4A4.")
else:
print("Enter a fault code.")
label = Label(top, text=entry_text)
label.pack()
或者您可以在Entry 中按Enter 时将<Return> 绑定到Entry 以运行函数。 Tkinter 将以event 作为参数运行函数,因此函数必须获取此参数。
E = Entry(top, text='var', textvariable=var, bd=5)
E.pack()
E.bind('<Return>', faultCodes)
def faultCodes(event):
entry_text = var.get()
if entry_text == "500" or entry_text == "514":
print("Follow fault code 9621F4A4.")
else:
print("Enter a fault code.")
label = Label(top, text=entry_text)
label.pack()
如果您使用event=None,您甚至可以将这两种方法用于相同的功能
完整的工作示例
from tkinter import *
def faultCodes(event=None):
entry_text = var.get()
if entry_text == "500" or entry_text == "514":
print("Follow fault code 9621F4A4.")
else:
print("Enter a fault code.")
label = Label(top, text=entry_text)
label.pack()
top = Tk()
var = StringVar()
E = Entry(top, text='var', textvariable=var, bd=5)
E.pack()
E.bind('<Return>', faultCodes)
B = Button(top, text='OK', command=faultCodes)
B.pack()
top.mainloop()
顺便说一句:var.get() 给出了字符串,所以我与字符串“500”、“514”进行比较——而不是整数 500、514。
编辑:Label的示例
from tkinter import *
# --- function ---
def faultCodes(event=None):
entry_text = var.get()
if entry_text == "500" or entry_text == "514":
label['text'] = "Follow fault code 9621F4A4."
else:
label['text'] = "Enter a fault code."
# --- main ---
top = Tk()
var = StringVar()
E = Entry(top, text='var', textvariable=var, bd=5)
E.pack()
E.bind('<Return>', faultCodes)
B = Button(top, text='OK', command=faultCodes)
B.pack()
label = Label(top, text='')
label.pack()
top.mainloop()
编辑: 字典示例
from tkinter import *
data = {
"500": "Follow fault code 9621F4A4.",
"514": "Follow fault code 9621F4A4.",
# ...add more ...
}
# --- function ---
def faultCodes(event=None):
entry_text = var.get()
if entry_text in data:
label['text'] = data[entry_text]
else:
label['text'] = "Enter a fault code."
# --- main ---
top = Tk()
var = StringVar()
E = Entry(top, text='var', textvariable=var, bd=5)
E.pack()
E.bind('<Return>', faultCodes)
B = Button(top, text='OK', command=faultCodes)
B.pack()
label = Label(top, text='')
label.pack()
top.mainloop()