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

2024-09-30 18:18:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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()

Tags: of字符串列表piece情况rootlist括号
1条回答
网友
1楼 · 发布于 2024-09-30 18:18:40

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

相关问题 更多 >