有没有办法知道何时单击tkinter组合框选项?



tkinter中,Buttons有一个名为command的参数,每当单击按钮时,它都会使某些函数运行。

tkinter Combobox的选项也可以这样做吗?

例如:

我在tkinter Combobox中有三个选项:#1#2#3

现在,只要#1被点击或点击,我就想打印出类似Options 1 Selected的东西。

可以做到吗?

P.S.,正如@Atlas435指出的关于从tk.Combobox()中获取所选值,我真的不想要Combobox()的值,我问的是是否有办法使Combobox选项像Buttons一样工作,当单击时,会导致某些函数执行。

看看这个例子,它满足了你的要求:

from tkinter import *
from tkinter import ttk
root = Tk()
def select(event): #the function to get triggered each time you choose something
if c.get() == lst[0]: #if it is the first item
print('Option 1 is selected')
elif c.get() == lst[1]: #if it is the second item
print('Option 2 is selected')
else: #or if it is the third item
print('Option 3 is selected')
lst = ['#1','#2','#3'] #creating option list
c = ttk.Combobox(root,values=lst,state='readonly') #creating a combobox
c.current(0) #setting first element as the item to be showed
c.pack(padx=10,pady=10) #putting on screen
c.bind('<<ComboboxSelected>>',select) #the event that your looking for 
root.mainloop()

我评论它是为了更好地理解,如果有任何疑问或错误,请告诉我

最新更新