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()
这是一个使用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()