【问题标题】:How to add titles to multiple OptionMenu's in tkinter?如何在 tkinter 中为多个 OptionMenu 添加标题?
【发布时间】:2021-05-26 07:06:57
【问题描述】:

我有以下 3 个列表:

owner = ['Spain', 'United Kingdom', 'Malaysia']
phase= ['A100', 'B100', 'C100']
machine = ['LLT', 'AAF', 'GGG', 'TGF']

通过上面的列表,我正在尝试制作 3 个 OptionMenus,效果很好。但是,当我尝试添加标题时,它看起来并不整洁。

这是我的代码:

window = Tk()
window.title("Running Python Script") #Create window
window.geometry('550x300') #geo of the window

def run():
    os.system('python "c:\data\FF\Desktop\PythonFolder\FF_software.py"') 

#The run button (this button runs some other software)
run_button = Button(window, text="Run your Code!", bg="blue", fg="white",command=run)
run_button.grid(column=0, row=0)

#These are the option menus
dd_owner = StringVar(window)
dd_owner.set(owner[0]) #the first value

dd_phase= StringVar(window)
dd_phase.set(phase[0]) 

dd_machine= StringVar(window)
dd_machine.set(machine[0])

w = OptionMenu(window, dd_owner, *owner)
w2 = OptionMenu(window, dd_phase, *phase)
w3 = OptionMenu(window, dd_machine, *machine)

#These are the titles
l1 = Label(window,  text='Select Owner', width=15 )  
l1.grid(row=5,column=1)

l2 = Label(window,  text='Select phase', width=15 )  
l2.grid(row=6,column=1)

l3 = Label(window,  text='Select machine', width=15 )  
l3.grid(row=7,column=1)

w.grid()
w2.grid()
w3.grid()

mainloop()

这是我的结果:

如您所见,它看起来不是很整洁。标题位于选项菜单上方,而不是左侧。

【问题讨论】:

  • 为什么没有为菜单指定任何网格坐标?
  • @mkrieger1 我完全忘记了,这能解决问题吗?
  • 你试试就知道了。
  • @mkrieger1 是的。好的,顺便说一句,谢谢。有没有办法让我的代码更短?因为当我有大约 10+optionMenus 时,我只是继续复制上面的 sn-ps 代码..
  • @TangerCity 您可以将它们存储在字典中并循环遍历键值。将标签文本作为dict 键,将您的选项菜单值作为dict 的值。现在您可以简单地遍历它们并缩短您的代码。

标签: python tkinter tkinter.optionmenu


【解决方案1】:
w.grid(row=5,column=2)
w2.grid(row=6,column=2)
w3.grid(row=7,column=2)

用这个替换最后 3 行,你就完成了。 您可以根据需要更改列值

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
  • 2021-01-03
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
相关资源
最近更新 更多