简体   繁体   English

将tkinter Optionmenu的标题设置为字符串和StringVar

[英]set tkinter Optionmenu's title to a string and a StringVar

So I have an Optionmenu with a title "options" and some options there. 因此,我有一个标题为“ options”的Optionmenu,那里还有一些选项。 The title changes every time I choose something to variable1. 每次我选择变量1时标题都会更改。 How can I set it after it changes, to a string "options" and to variable's value? 更改后如何设置为字符串“ options”和变量的值? For example: "options - music off" I tried this, but it doesn't work: 例如:“选项-音乐关闭”,我尝试了此操作,但不起作用:

variable1 = StringVar() 
variable1.set("something",variable1)

Thanks. 谢谢。

Edit: Here is a complete version of my code: 编辑:这是我的代码的完整版本:

            options = Menubutton(frame,textvariable = options3,indicatoron=True,borderwidth=1, relief="raised", width=20)
            options.grid(row=3,column=2)#options2 [0] options3
            main_menu = Menu(options,tearoff=False)
            options.configure(menu=main_menu)
            get_options3= options3.get()
            neededstring = string+str(options3)
            print("needed str", neededstring)
            options3.set('options - ' +options3.get())
            for item in (("Answer with text", "plain text", "only numbers", "only letters"),
             ("Answer with Checkbuttons", "red", "green", "blue"), ("Answer with Radiobuttons", "one option can be chosed")
                         ):
                menu = Menu(main_menu, tearoff=False)
                main_menu.add_cascade(label=item[0], menu=menu)
                for value in item[1:]:
                    menu.add_radiobutton(value=value, label=value, variable=options3)

If you trace the StringVar you give to the OptionMenu, you can add the string onto the front whenever the option is changed. 如果您跟踪提供给OptionMenu的StringVar,则可以在更改选项时将字符串添加到最前面。 This creates a window with an OptionMenu that does this: 这将创建一个带有OptionMenu的窗口,该窗口可以执行以下操作:

import tkinter as tk

root = tk.Tk()

# function to add 'options - ' to the front of the selected option
def change_selected(var1):
    var1.set('options - %s' % var1.get())

# variable
var1 = tk.StringVar(root)
var1.set('1')

# create menu
options = tk.OptionMenu(root, var1, '1', '2', '3')
options.pack()

# trace variable for changes
var1.trace('w', lambda *args: change_selected(var1))

root.mainloop()

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

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