如何使用Tkinter为特定输入返回警报?

问题描述

我使用Tkinter创建了一个模拟搜索引擎。我希望用户搜索引擎中输入单词“ test”,然后点击“提交”。这应该返回一个警报。如果用户插入单词“ test”以外的任何内容,那么我希望搜索引擎不返回任何内容。我已经为模拟搜索引擎创建了界面,但是接受用户输入的部分不起作用。这是我的代码如下:

import tkinter as tk
root = tk.Tk()
canvas1=tk.Canvas(root,width=400,height=300,relief='raised')
canvas1.pack()
label1 = tk.Label(root,text='LookUp')
label1.config(fg='blue',font=('times',30,'bold'))
canvas1.create_window(200,100,window=label1)
entry1 = tk.Entry (root)
canvas1.create_window(200,140,window=entry1)

def values():
     userinput = tk.StringVar(entry1.get())
     if userinput == 'test':
             Output = ('Alert Executed')
             label_Output = tk.Label(root,text=Alert,bg='red')
             canvas1.create_window(270,200,window=label_Output)                     

     else:
             Output = ('')
             label_Output = tk.Label(root,text= Alert)
             canvas1.create_window(270,window=label_Output)

button1=tk.Button(root,text='Search',command=values,bg='green',fg='white')
canvas1.create_window(200,180,window=button1)

root.mainloop()

解决方法

userinput变量需要引用entry1.get()

label_Output需要将您的Output变量作为其text

import tkinter as tk
root = tk.Tk()
canvas1=tk.Canvas(root,width=400,height=300,relief='raised')
canvas1.pack()
label1 = tk.Label(root,text='LookUp')
label1.config(fg='blue',font=('times',30,'bold'))
canvas1.create_window(200,100,window=label1)
entry1 = tk.Entry (root)
canvas1.create_window(200,140,window=entry1)

def values():
     userinput = entry1.get()
     if userinput == 'test':
             Output = ('Alert Executed')
             label_Output = tk.Label(root,text=Output,bg='red')
             canvas1.create_window(270,200,window=label_Output)                     

     else:
             Output = ('')
             label_Output = tk.Label(root,text= Output)
             canvas1.create_window(270,window=label_Output)

button1=tk.Button(root,text='Search',command=values,bg='green',fg='white')
canvas1.create_window(200,180,window=button1)

root.mainloop()