在使用ttk OptionMenu时,有多种方法可以防止回调函数被触发两次:
import tkinter as tk
from tkinter import ttk
def callback(*args):
print("OptionMenu selected:", var.get())
root = tk.Tk()
var = tk.StringVar()
option_menu = ttk.OptionMenu(root, var, "Option 1", "Option 2", "Option 3", command=callback)
option_menu.pack()
root.mainloop()
import tkinter as tk
from tkinter import ttk
def callback():
if not callback.called:
callback.called = True
print("OptionMenu selected:", option_var.get())
root = tk.Tk()
callback.called = False
option_var = tk.StringVar()
option_menu = ttk.OptionMenu(root, option_var, "Option 1", "Option 2", "Option 3", command=callback)
option_menu.pack()
root.mainloop()
import tkinter as tk
from tkinter import ttk
def callback(event):
print("OptionMenu selected:", option_var.get())
root = tk.Tk()
option_var = tk.StringVar()
option_menu = ttk.OptionMenu(root, option_var, "Option 1", "Option 2", "Option 3")
option_menu.bind("<<ComboboxSelected>>", callback)
option_menu.pack()
root.mainloop()
这些方法都可以有效地防止ttk OptionMenu回调函数被触发两次,并根据具体情况选择最合适的方法进行使用。
参考链接:
领取专属 10元无门槛券
手把手带您无忧上云