如何在 tkinter 中的组合框中设置默认值?

我正在创建一个需要 tkinter 组合框的应用程序。我希望组合框从应用程序启动时就具有默认值。我已经尝试过current()方法但它不起作用。


这是我的代码片段


n= tk.StringVar()

youtubechoicesLabel = ttk.Combobox(root, font=font, justify='center', textvariable=n)

youtubechoicesLabel['values'] = ("----Download Type----",

                                    "Mp4  720p",

                                    "Mp4  144p",

                                    "Video  3gp",

                                    "Audio  Mp3")


youtubechoicesLabel.current(0)

youtubechoicesLabel["background"] = '#ff0000'

youtubechoicesLabel["foreground"] = '#ffffff'

youtubechoicesLabel.pack(side=TOP, pady=20)


跃然一笑
浏览 137回答 3
3回答

守候你守候我

调用current()是正确的并且正在运行 - 由于使用了foreground您指定的白色,您只是看不到当前的选择。n = tk.StringVar()youtubechoicesLabel = ttk.Combobox(root, font=font, justify='center', textvariable=n)youtubechoicesLabel['values'] = ("----Download Type----",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Mp4&nbsp; 720p",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Mp4&nbsp; 144p",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Video&nbsp; 3gp",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Audio&nbsp; Mp3")youtubechoicesLabel.current(0)youtubechoicesLabel["background"] = '#ff0000'#youtubechoicesLabel["foreground"] = '#ffffff'&nbsp; # <----- DISABLEDyoutubechoicesLabel.pack(side=TOP, pady=20)

蓝山帝景

只需设置n的值即可。n.set('default&nbsp;value')

茅侃侃

您需要禁用foreground颜色并将事件绑定到组合框。我遇到了同样的问题,上述解决方案对我不起作用。我通过将事件绑定到它来修复它。n = tk.StringVar()youtubechoicesLabel = ttk.Combobox(window, justify='center', textvariable=n)youtubechoicesLabel['values'] = ("----Download Type----",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Mp4&nbsp; 720p",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Mp4&nbsp; 144p",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Video&nbsp; 3gp",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Audio&nbsp; Mp3")youtubechoicesLabel["background"] = '#ff0000'#youtubechoicesLabel["foreground"] = '#ffffff' #disable it as martineau saidyoutubechoicesLabel.pack(side=tk.TOP, pady=20)youtubechoicesLabel.current(0)#bind an event to your youtubechoicesLabeldef ComboboxEvent(event):&nbsp; &nbsp; print("some event")youtubechoicesLabel.bind("<<ComboboxSelected>>", ComboboxEvent)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python