简体   繁体   English

在 tkinter OptionMenu 中的所选项目旁边添加一个检查

[英]Adding a check next to the selected item in tkinter OptionMenu

How could I add a check sign next to the currently selected item (or highlight it) in a OptionMenu in a tkinter GUI?如何在 tkinter GUI 的 OptionMenu 中当前选定的项目(或突出显示)旁边添加复选符号? The idea is that when I click again to select another item, I can see easily which one is selected (similar to the following picture)思路是,当我再次点击选择另一个项目时,我可以很容易地看到选择了哪个(类似于下图)

在此处输入图片说明

I just added a new example:我刚刚添加了一个新示例:

from tkinter import *

OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
] 

app = Tk()

app.geometry('100x200')

variable = StringVar(app)
variable.set(OptionList[0])

opt = OptionMenu(app, variable, *OptionList)
opt.config(width=90, font=('Helvetica', 12))
opt.pack(side="top")


labelTest = Label(text="", font=('Helvetica', 12), fg='red')
labelTest.pack(side="top")

def callback(*args):
    labelTest.configure(text="The selected item is {}".format(variable.get()))

variable.trace("w", callback)

app.mainloop()

Just use ttk widgets for this modern looking style, try saying something like:只需将ttk小部件用于这种现代外观风格,尝试说如下:

from tkinter import ttk
....
     #arguments  -  master  variable     default      *values
opt = ttk.Optionmenu(app, variable, OptionList[0], *OptionList)

The effect given by this is pretty similar or maybe identical to what your trying to achieve.由此产生的效果与您尝试实现的效果非常相似或可能相同。

You might notice an additional third positional argument here, it is actually default=OptionList[0] argument specified here(specific to just ttk.Optionmenu ), it is just the default value that the optionmenu will display, ignoring this might lead to some bugs in the looks of optionmenu, like this .你可能会注意到这里有一个额外的第三个位置参数,它实际上是这里指定的default=OptionList[0]参数(特定于ttk.Optionmenu ),它只是选项菜单将显示的默认值,忽略这可能会导致一些错误在选项菜单的外观中,像这样

And also keep in mind, it does not have a font option too.还要记住,它也没有font选项。 To overcome this, check this out为了克服这个,看看这个

Hope this was of some help to you, do let me know if any errors or doubts.希望这对您有所帮助,如果有任何错误或疑问,请告诉我。

Cheers干杯

You can get similar effect using tk.OptionMenu :您可以使用tk.OptionMenu获得类似的效果:

from tkinter import *

OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
] 

app = Tk()

app.geometry('300x200')

variable = StringVar(app)
variable.set(OptionList[0])

opt = OptionMenu(app, variable, None) # need to supply at least one menu item
opt.config(width=90, font=('Helvetica', 12))
opt.pack(side="top")

# populate the menu items
menu = opt['menu']
menu.delete(0) # remove the None item
for item in OptionList:
    menu.add_radiobutton(label=item, variable=variable)

labelTest = Label(text="", font=('Helvetica', 12), fg='red')
labelTest.pack(side="top")

def callback(*args):
    labelTest.configure(text="The selected item is {}".format(variable.get()))

variable.trace("w", callback)

app.mainloop()

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

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