【问题标题】:Automatically updating a value through a OptionMenu tkinter object通过 OptionMenu tkinter 对象自动更新值
【发布时间】:2020-08-10 20:04:26
【问题描述】:

我想编写一个 tkinter 应用程序,它会根据 OptionMenu 对象的当前状态自动更新一个值。这是我目前所拥有的

from tkinter import *
root = Tk()

def show():
  myLabel=Label(root,text=clicked.get()).pack()

clicked=StringVar()
clicked.set("1")

drop = OptionMenu(root,clicked,"1","2","3")
drop.pack()

myButton = Button(root,text="show selection",command=show)

root.mainloop()

在此版本中,只能通过单击按钮来更新文本。如果没有这个“中间人”,我怎样才能使文本自动更新?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    You can simply assign clicked to the textvariable of the Label, then whenever an option is selected, the label will be updated:

    import tkinter as tk
    
    root = tk.Tk()
    
    clicked = tk.StringVar(value="1")
    
    drop = tk.OptionMenu(root, clicked, "1", "2", "3")
    drop.pack()
    
    tk.Label(root, textvariable=clicked).pack()
    
    root.mainloop()
    

    【讨论】:

    • 谢谢你!
    【解决方案2】:

    改变一些东西后,我得到了它的工作。

    最好使用config()函数来改变item的属性,另一个重要的事情是不要pack()对象(在本例中为标签)与变量声明在同一行。

    这样,您将能够更改文本。这是您的代码更新!

    from tkinter import *
    
    def show():
        myLabel.config(text = clicked.get())
    
    root = Tk()
    clicked=StringVar( value="1")
    
    myLabel=Label(root, text="click the button at the bottom to see this label text changed")
    myLabel.pack()
    
    drop = OptionMenu(root, clicked, "1","2","3")
    drop.pack()
    
    myButton = Button(root, text="show selection", command=show)
    myButton.pack()
    
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      相关资源
      最近更新 更多