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

时间:2018-09-05 19:38:37

标签: python python-3.x tkinter

因此,我有一个带有标题“ options”的Optionmenu和一些选项。每次我选择变量1时标题都会更改。更改后如何设置为字符串“ options”和变量的值? 例如:“选项-音乐关闭” 我试过了,但是没用:

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

谢谢。

编辑:这是我的代码的完整版本:

            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)

1 个答案:

答案 0 :(得分:0)

如果您跟踪提供给OptionMenu的StringVar,则可以在更改选项时将字符串添加到最前面。这将创建一个带有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()