Tkinter之部件3种放置方式pack、grid、place

import Tkinter as tk 
window = tk.Tk()
window.title('My Window')
window.geometry('500x300')  
 
#pack
#常用的pack(), 多数按照上和西的方式排列,不指定时默认为上。
tk.Label(window,text='123nihao你好',fg='red').pack(side='top')       # 上
tk.Label(window,text='123nihao你好',fg='red').pack(side='bottom') # 下
tk.Label(window,text='123nihao你好',fg='red').pack(side='left')      # 左
tk.Label(window,text='123nihao你好',fg='red').pack(side='right')   # 右
 
tk.Label(window,text='123nihao你好',fg='red').pack(anchor='n')    # 北,效果同上
tk.Label(window,text='123nihao你好',fg='red').pack(anchor='s')    # 南,效果同上
tk.Label(window,text='123nihao你好',fg='red').pack(anchor='w')  # 西
tk.Label(window,text='123nihao你好',fg='red').pack(anchor='e')   # 东
 
可以体会下这两种的不同表现:
for i in range(3):
    tk.Radiobutton(window, text=i).pack(anchor='w')  #按行追加,前三行依次靠西生成3个按钮
 
for i in range(3):
    tk.Radiobutton(window, text=i).pack(side='left')   #同一行追加,中间一行依次靠上一按钮生成3个按钮
 
#grid
#以规律的方格形式呈现。比如下面的代码就是创建一个三行三列的表格:参数row 为行,colum 为列,padx 单元格左右间距,pady单元格上下间距,ipadx单元格内部元素与单元格的左右间距,ipady单元格内部元素与单元格的上下间距。
for i in range(3):
    for j in range(3):
      l=tk.Label(window,text='123nihao你好',bg='yellow',font=('Arial', 12), width=10, height=2)
       l.grid(row=i, column=j, padx=5, pady=10, ipadx=1, ipady=20)
    
#place
#用精确的坐标来定位,参数anchor='nw'表示锚定点是西北角。
tk.Label(window, text='Pl', font=('Arial', 20), ).place(x=20, y=100, anchor='nw')
tk.Label(window, text='Pl', font=('Arial', 20), ).place(x=20, y=200, anchor='nw')
tk.Label(window, text='Pl', font=('Arial', 20), ).place(x=80, y=100, anchor='nw')
tk.Label(window, text='Pl', font=('Arial', 20), ).place(x=80, y=200, anchor='nw')
       
window.mainloop()
 
 
 
注意
3种方式不要混在一起同时执行,会导致程序卡掉,暂不清楚原因。
 
3种方式都支持两行并一行:
w=tk.Label(window,text='123mn你好',fg='red')
w.pack(side='top')
等于:
tk.Label(window,text='123mn你好',fg='red').pack(side='top')
 
但是:
tk.Label(window,text='123mn你好',fg='red').pack(side='top')       # 上
tk.Label(window,text='123mn你好',fg='red').pack(side='bottom') # 下
会表示为2个Label部件。
 
w=tk.Label(window,text='123mn你好',fg='red')
w.pack(side='top')
w.pack(side='bottom')
却只表示1个Label部件,只取最后的bottom。
 
w=tk.Label(window,text='123mn你好',fg='red')
w.pack(side='top')
w=tk.Label(window,text='123mn你好',fg='red')
w.pack(side='bottom')
这样写就能表示2个Label部件。
 
综合来看,多个部件时还是一行的写法更方便。
 
 
 
原文地址:https://www.cnblogs.com/myshuzhimei/p/11764532.html