python tkinter如何组织行和列

时间:2017-08-06 10:43:44

标签: python-2.7 tkinter grid

您好我正在尝试构建用户界面并且列位和行位置存在问题。我期望看到的是按钮和入口小部件之间的距离,因为我在它们之间留下了两个空列。那么为什么他们站在入口小部件旁边并改变入口区域之间的距离?有谁可以给​​我一些帮助吗?

这是代码......

from Tkinter import*

HMCC=Tk()

HMCC.title(" GUI v1.0 ")
HMCC.geometry("500x300")

entry_1 = Entry(HMCC)
entry_2 = Entry(HMCC)
entry_3 = Entry(HMCC)
entry_4 = Entry(HMCC)
entry_5 = Entry(HMCC)
entry_6 = Entry(HMCC)
entry_7 = Entry(HMCC)
entry_8 = Entry(HMCC)

entry_1.grid(row=2,column=1)
entry_2.grid(row=3,column=1)
entry_3.grid(row=4,column=1)
entry_4.grid(row=5,column=1)
entry_5.grid(row=6,column=1)
entry_6.grid(row=7,column=1)
entry_7.grid(row=8,column=1)
entry_8.grid(row=9,column=1)

Channel_1 = Label(HMCC, text = "Channel 1 : ")
Channel_2 = Label(HMCC, text = "Channel 2 : ")
Channel_3 = Label(HMCC, text = "Channel 3 : ")
Channel_4 = Label(HMCC, text = "Channel 4 : ")
Channel_5 = Label(HMCC, text = "Channel 5 : ")
Channel_6 = Label(HMCC, text = "Channel 6 : ")
Channel_7 = Label(HMCC, text = "Channel 7 : ")
Channel_8 = Label(HMCC, text = "Channel 8 : ")

Channel_1.grid( row = 2, column = 0, sticky = E)    
Channel_2.grid( row = 3, column = 0, sticky = E)    
Channel_3.grid( row = 4, column = 0, sticky = E)
Channel_4.grid( row = 5, column = 0, sticky = E)    
Channel_5.grid( row = 6, column = 0, sticky = E)    
Channel_6.grid( row = 7, column = 0, sticky = E)    
Channel_7.grid( row = 8, column = 0, sticky = E)
Channel_8.grid( row = 9, column = 0, sticky = E)

#button1 = Button(text="   START   " , fg="red"  )
#button2 = Button(text=" PAUSE "     , fg="blue" )
#button3 = Button(text="    STOP    ", fg="green")
#button4 = Button(text="QUIT"        , fg="black",command=HMCC.quit) 

#button1.grid( row = 1, column = 3)
#button2.grid( row = 2, column = 3)
#button3.grid( row = 3, column = 3)
#button4.grid( row = 4, column = 3) 

HMCC.mainloop()

Current view

提前致谢

1 个答案:

答案 0 :(得分:1)

如果第2列中没有任何内容,则tkinter将忽略它。

除了上面发布的评论中包含您问题的答案之外,您只需使用循环即可显着清理代码:

num_rows = 8
entries = [None]*num_rows
channels = [None]*num_rows

for i in range(num_rows):
    channels[i] = Label(HMCC, text = "Channel {0} : ".format(i+1))
    channels[i].grid(row=i+2,column=0,sticky=E)
    entries[i] = Entry(HMCC)
    entries[i].grid(row=i+2, column=1)

更好的是,使用列表理解:

num_rows = 8

entries = [Entry(HMCC).grid(row=i+2, column=1) for i in range(num_rows)]
channels = [Label(HMCC, text = "Channel {0} : ".format(i)).grid(row=i+2,column=0,sticky=E) for i in range(num_rows)]