有没有办法仅在 tkinter 选项菜单的选项发生更改时才执行函数?

问题描述 投票:0回答:1

使用 tkinter OptionMenu 时,命令输入可让您激活某个功能,但即使您单击已设置的选项,也会激活相同的功能。示例:设置了选项“A”,您再次单击选项“A”,该命令将激活,但是我希望只有当我将选择从“A”更改为另一个不是“A”的选项时才会发生这种情况,例如“ B”或“C”,反之亦然。

这是我的代码:

import tkinter 
from tkinter import *

# Create window------------------------------------------
window = tkinter.Tk()
window.title("Window")
window.geometry("800x500")
#--------------------------------------------------------

# Function-----------------------------------------------
def print_message(*args):
    print("the option has been changed")
#--------------------------------------------------------

# Dropdown menu------------------------------------------
# Datatype
option_selected = StringVar()  
# Create dropdown menu
option_list = ["A", "B", "C"]
option_selected.set(option_list[0]) 
option_menu = OptionMenu(window, option_selected, *option_list)
option_menu.pack()
option_selected.trace("w",print_message)
#--------------------------------------------------------

# Maintain window open
window.mainloop()
python tkinter optionmenu
1个回答
0
投票

基本上

OptionMenu
不支持此类功能,但是您可以创建自定义
OptionMenu
来提供此类功能:

import tkinter as tk

class CustomOptionMenu(tk.OptionMenu):
    def __init__(self, master, var, *values, command=None):
        super().__init__(master, var, *values,
                         command=self.on_selected if command else None)
        self.command = command
        self.value = var.get()

    def on_selected(self, value):
        # execute callback only if selected value is changed
        if self.value != value:
            self.command(value)
            self.value = value  # save the selected value

# Create window------------------------------------------
window = tk.Tk()
window.title("Window")
window.geometry("800x500")
#--------------------------------------------------------

# Function-----------------------------------------------
def print_message(value):
    print(f"the option has been changed to {value}")
#--------------------------------------------------------

# Dropdown menu------------------------------------------
# Datatype
option_selected = tk.StringVar()
# Create dropdown menu
option_list = ["A", "B", "C"]
option_selected.set(option_list[0])
option_menu = CustomOptionMenu(window, option_selected, *option_list, command=print_message)
option_menu.pack()
#--------------------------------------------------------

# Maintain window open
window.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.