【问题标题】:How can I change the state of a menu with a button inside tkinter?如何使用 tkinter 中的按钮更改菜单的状态?
【发布时间】:2019-10-10 02:03:05
【问题描述】:

我想在 tkinter 中制作一个单位转换器。我做了两个下拉菜单;第一个允许用户选择他们想要转换的单位,第二个允许他们选择他们想要转换的单位。我想在第二个菜单中选择一个选项后禁用所有在第二个菜单中没有意义的选项(如果他们想转换公斤,在第二个菜单中选择厘米是没有意义的)

我尝试使用 StringVar() 来更改菜单的状态,但它不起作用。我不知道下一步该做什么。我一直在使用 Tutorialspoint 的文档,但我找不到任何有用的东西(第一次使用 tkinter)。

import tkinter as tk

root = tk.Tk()
root.geometry('600x600')

my_var = tk.StringVar()
my_var.set('active')

unit_1 = tk.Menubutton(root,text='This is the first menu button',bg='white',activebackground='#2E64FE',activeforeground='#FFFFFF')

menu_1 = tk.Menu(unit_1)
unit_1.config(menu=menu_1)

menu_1.add_command(label='Inches',command= lambda: my_var.set('disabled') )

menu_1.add_command(label='Kilograms')

unit_2 = tk.Menubutton(root,text='This is the second menu button',bg='white',activebackground='#2E64FE',activeforeground='#FFFFFF')

menu_2 = tk.Menu(unit_2)
unit_2.config(menu=menu_2)

menu_2.add_command(label='Centimeters')

menu_2.add_command(label='Pounds',state= my_var.get())

unit_1.place(relx=0.03,rely=0.08,relheight=0.04,relwidth=0.45)
unit_2.place(relx=0.52,rely=0.08,relheight=0.04,relwidth=0.45)

root.mainloop()

在这里,我试图在第一个菜单中设置“英寸”按钮以禁用第二个菜单中的“磅”按钮,但是当我单击“英寸”时,“磅”没有任何反应。

【问题讨论】:

    标签: python-3.x tkinter


    【解决方案1】:

    tk.StringVar() 用于更改某些内容的文本,例如,如果您想要一个带有动态文本的按钮,您可能需要为此使用tk.StringVar()

    你想做的是不同的事情;您想更改标签的配置。所以你需要找到元素并调整它的状态:

    import tkinter as tk
    
    root = tk.Tk()
    root.geometry('600x600')
    
    my_var = tk.StringVar()
    my_var.set('active')
    
    unit_1 = tk.Menubutton(root,text='This is the first menu button',bg='white',activebackground='#2E64FE',activeforeground='#FFFFFF')
    
    menu_1 = tk.Menu(unit_1)
    unit_1.config(menu=menu_1)
    
    menu_1.add_command(label='Inches', command=lambda: disable_pounds())
    
    menu_1.add_command(label='Kilograms', command=lambda: disable_centimeters())
    
    unit_2 = tk.Menubutton(root,text='This is the second menu button',bg='white',activebackground='#2E64FE',activeforeground='#FFFFFF')
    
    menu_2 = tk.Menu(unit_2)
    unit_2.config(menu=menu_2)
    
    menu_2.add_command(label='Centimeters')
    
    menu_2.add_command(label='Pounds',state= my_var.get())
    
    unit_1.place(relx=0.03,rely=0.08,relheight=0.04,relwidth=0.45)
    unit_2.place(relx=0.52,rely=0.08,relheight=0.04,relwidth=0.45)
    
    
    def disable_pounds():
        menu_2.entryconfig("Pounds", state="disabled")
        menu_2.entryconfig("Centimeters", state="active")
    
    
    def disable_centimeters():
        menu_2.entryconfig("Pounds", state="active")
        menu_2.entryconfig("Centimeters", state="disabled")
    
    
    
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 2021-02-13
      • 2020-01-23
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多