在tkinter的每个选项菜单中添加标签

问题描述:

我有一个小部件,其中有许多不同的选项菜单。我需要在每个选项菜单左侧添加适当的标签。在tkinter的每个选项菜单中添加标签

我的代码如下所示:

from tkinter import* 

class MyOptionMenu(OptionMenu): 
    def __init__(self, master, status, *options): 
     self.var = StringVar(master) 
     self.var.set(status) 
     OptionMenu.__init__(self, master, self.var, *options) 
     self.config(font=('calibri',(8)),bg='white',width=20) 
     self['menu'].config(font=('calibri',(8)),bg='white') 


root = Tk() 
optionList1 = items1 
optionList2 = items2 
optionList3 = items3 
optionList4 = items4 
optionList5 = items5 
lab1 = Label(root, text="condition №1", font="Arial 8", anchor='w') 
mymenu1 = MyOptionMenu(root, '-', *optionList1) 
lab2 = Label(root, text="condition №2", font="Arial 8", anchor='w') 
mymenu2 = MyOptionMenu(root, '-', *optionList2) 
lab3 = Label(root, text="condition №3", font="Arial 8", anchor='w') 
mymenu3 = MyOptionMenu(root, '-', *optionList3) 
lab4 = Label(root, text="condition №4", font="Arial 8", anchor='w') 
mymenu4 = MyOptionMenu(root, '-', *optionList4) 
lab = Label(root, text="Enter the date", font="Arial 8", anchor='w') 
ent1 = Entry(root,width=20,bd=3) 
lab5 = Label(root, text="condition №5", font="Arial 8", anchor='w') 
mymenu5 = MyOptionMenu(root, '-', *optionList5) 
lab1.pack(side="top",fill = "x") 
mymenu1.pack(side="top",fill = "y") 
lab2.pack(side="top",fill = "x") 
mymenu2.pack(side="top",fill = "y") 
lab3.pack(side="top", fill="x") 
mymenu3.pack(side="top", fill="y") 
lab4.pack(side="top", fill="x") 
mymenu4.pack(side="top", fill = "y") 
lab.pack(side="top", fill="x") 
ent1.pack(side="top", fill="y") 
lab5.pack(side="top", fill="x") 
mymenu5.pack(side="top", fill = "y") 

def save_selected_values(): 
    global values1 
    values1 = [mymenu1.var.get(), mymenu2.var.get(), mymenu3.var.get(), mymenu4.var.get(), ent1.get(), mymenu5.var.get()] 
    print(values1) 

button = Button(root, text="OK", command=save_selected_values) 
button.pack() 
root.mainloop() 

结果看起来是这样的:

The result looks like this

但我需要每一个标签是在一个下拉列表

相应的行

在Excel中看起来像这样:

enter image description here

其中列B中的每一行都是一个下拉列表。

据我所知,fill = "x"填补了整条线,但是当我尝试改变它时,它看起来更糟。

我将不胜感激任何意见!

作为您给定的Excel示例,我将使用grid geometry manager作为您的用途,它将项目放置在网格布局中。有了它你可以指定行和列。我还会将所有标签和下拉列表存储在列表中以便于访问。然后你可以使用:

for index, (lab, mymenu) in enumerate(zip(labels, mymenus)): 
    lab.grid(row=index, column=0) 
    mymenu.grid(row=index, column=1) 
+0

试图纠正语法。如果我的编辑改变了你想说的话,请随时回滚。 – Lafexlos

+1

@Lafexlos它确实改变了我的原意,但我的意思是说你的版本听起来更好,所以即使不回滚。最初我想说的是Asker在excel例子中使用了一个网格布局,所以我会在tkinter中使用它。 –