如何在用户在 tkinter 中启动事件之前使用事件驱动的 GUI 菜单的默认值,Python?

How to use the event driven GUI menu's default value, before user starts his events in tkinter, Python?

我的 GUI 中只有一个菜单。此菜单用于 select 哪个标签将被添加到 GUI。

当我启动程序时,菜单已经显示了默认选项 selected,但程序中的任何地方都没有使用这个选项。它需要用户的操作(单击并 select 在菜单中)才能从该菜单中获取内容。

我希望我的程序立即使用默认菜单的选项,以后可以由用户更改。 您能否不仅针对这个特定的标签相关任务给我提示,而且还给我一些一般提示?如何在程序中使用默认菜单值,不与菜单交互?

这是我的代码:

from tkinter import *

root=Tk()
root.title("test")
# root.geometry("400x400")

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

options=["a","b","c"]

clicked = StringVar()
clicked.set(options[0])

drop=OptionMenu(root,clicked,*options, command=selected)
drop.pack()
root.mainloop()

一个简单的方法:

from tkinter import *

root=Tk()
root.title("test")
# root.geometry("400x400")

def selected(event):
    myLabel['text'] = clicked.get()

options=["a","b","c"]

clicked = StringVar()
clicked.set(options[0])

drop=OptionMenu(root,clicked,*options, command=selected)
drop.pack()


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

root.mainloop()

或者我建议你使用textvariable,那么你就不需要使用函数来更改标签了:

from tkinter import *

root=Tk()
root.title("test")
# root.geometry("400x400")


options=["a","b","c"]

clicked = StringVar()
clicked.set(options[0])

drop=OptionMenu(root,clicked,*options)
drop.pack()


myLabel = Label(root, textvariable=clicked) # bind a textvariable
myLabel.pack()

root.mainloop()