简体   繁体   中英

Calling Different Functions tkinter

I'm trying to call different functions based on the inputted text in a Tkinter program.

root=Tk()
tex=Text(root)
tex.pack(side='right')
inputfield = Entry(root)
inputfield.pack(side='bottom')
text = inputfield.get()
if 'weather:' in text:
    inputfield.bind('<Return>', lambda _: weather())
if 'open:' in text:
     inputfield.bind('<Return>', lambda _: program())

root.mainloop()

I'm trying to make it so if the inputted text contains weather: then it will call the weather() function. But if the inputted text contains open: then it opens the program() function. However I cannot figure it out. Anyone have any suggestions?

You are retrieving the text of the Entry before the mainloop. Instead of that, you should check the content inside the callback function:

def callback(event):
    text = inputfield.get()
    if 'weather:' in text:
        weather()
    if 'open:' in text:
        program()

# ...
inputfield.bind('<Return>', callback)

Besides, if you bind two times the <Return> event, the second binding will override the previous one ( unless you pass "+" as the third argument ). However, with only one callback you have enough to control both scenarios.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM