繁体   English   中英

选择一个选项后,如何使Tkinter OptionMenu不更改文本?

[英]How can I make a Tkinter OptionMenu not change the text when an option is selected?

我想在Tkinter应用程序上创建一个文件按钮,向用户显示四个选项中的三个。 我有以下代码:

self.file_button_text = StringVar(master)
self.file_button_text.set('File')
self.file_buton = OptionMenu(self, self.file_button_text, "Com Ports", "Bottle Information", "Reset Graphs")
self.file_buton.grid(row=0, column=0)
self.file_button_text.trace("w", self.file_option)

def file_option(self, *args):
    print(self.file_button_text.get())
    self.file_button_text.set('File')

但是,一旦选择了一个选项,按钮的文本就会变为该选项。 有没有一种方法可以在不更改按钮本身文本的情况下获取选择的值? 我尝试使用trace查看选择的选项,然后将文本更改回File但是花费的时间太长。 是否有更好/另一种方式来做到这一点?

选项菜单不过是带有MenuMenubutton ,还有一些专门用于更改按钮文本的特殊代码。 如果您不需要该功能,只需使用MenubuttonMenu创建自己的Menu

例:

import tkinter as tk

root = tk.Tk()
var = tk.StringVar()
label = tk.Label(root, textvariable=var)
menubutton = tk.Menubutton(root, text="Select an option",
                           borderwidth=1, relief="raised",
                           indicatoron=True)
menu = tk.Menu(menubutton, tearoff=False)
menubutton.configure(menu=menu)
menu.add_radiobutton(label="One", variable=var, value="One")
menu.add_radiobutton(label="Two", variable=var, value="Two")
menu.add_radiobutton(label="Three", variable=var, value="Three")

label.pack(side="bottom", fill="x")
menubutton.pack(side="top")

root.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM