2017-07-31 47 views
0

我有一個小部件,其中有許多不同的選項菜單。我需要在每個選項菜單左側添加適當的標籤。在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"填補了整條線,但是當我嘗試改變它時,它看起來更糟。

我將不勝感激任何意見!

回答

2

作爲您給定的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中使用它。 –

相關問題