Automatically updating a value through a OptionMenu tkinter object

走远了吗. 提交于 2021-02-11 12:33:54

问题


I would like to write a tkinter app that will automatically update a value based on the current state of the OptionMenu object. Here's what I have so far

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()

In this version, the text can only be updated by clicking a button. How can I make the text update automatically, without this "middle man"?


回答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:


After changing some things, i got it working.

It is better to use the config() function to change item's attributes, and another important thing is to not pack() the objects (the Label, in this case) in the same line that the variable declaration.

Like so, you'll be able to change the text. Here is your code updated!

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()


来源:https://stackoverflow.com/questions/63347255/automatically-updating-a-value-through-a-optionmenu-tkinter-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!