Tkinter中的OptionMenu会自动为选项添加括号

问题描述 投票:-1回答:1

OptionMenu中的短语显示为“{Piece of cake}”而不是“Piece of cake”。它只发生在多字符串中。我确保字符串没有通过替换附加这些括号。当我打印我的列表时,括号不在那里,但在OptionMenu中它们是。谁知道原因?

from tkinter import *

root = Tk()
root.geometry('300x200')

ingredients = [('French fries', 'szt', 'D'), ('Salt', 'g', 'D'), ('Cake', 'szt', 'D'), ('Potatoes and eggs', 'g', 'D')]

chosen_ingredient = StringVar()
om_ingredients_list = OptionMenu(root, chosen_ingredient, *ingredients)
om_ingredients_list.config(width=12)
om_ingredients_list.pack(pady=10)

root.mainloop()
python tkinter
1个回答
0
投票

这是一个使用format函数创建选项的示例。

from tkinter import *

root = Tk()
root.geometry('300x200')

ingredients = [('French fries', 'szt', 'D'), ('Salt', 'g', 'D'),
               ('Cake', 'szt', 'D'), ('Potatoes and eggs', 'g', 'D')]

# Extract first and second item from tuple with format function
options = ['{} ({})'.format(*item) for item in ingredients] 
chosen_ingredient = StringVar()
om_ingredients_list = OptionMenu(root, chosen_ingredient, *options)
om_ingredients_list.config(width=20)
om_ingredients_list.pack(pady=10)

root.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.