美文网首页Python 专题
小鱼儿学Tkinter-Pack布局

小鱼儿学Tkinter-Pack布局

作者: 小鱼儿_yzh | 来源:发表于2022-06-27 17:34 被阅读0次

    tkinter 有三种布局管理方式:

    · pack · grid · place
    注意这三种布局管理在同一个 master window 里一定不可以混用!

    布局管理有以下功能:

    • 将控件放置在屏幕上,包括控件的位置及控件的大小
    • 将控件注册到本地窗口系统中
    • 管理控件在屏幕上的显示

    虽然控件自己也可以指定大小和对齐方式等信息, 但最终的控件大小及位置还是由布局管理决定的.

    Pack 布局管理

    • pack 是三种布局管理中最常用的.
    • 另外两种布局需要精确指定控件具体的显示位置, 而 pack 布局可以指定相对位置, 精确的位置会由 pack 系统自动完成. 这也使得 pack 布局没有另外两种布局方式灵活.
    • pack 是简单应用的首选布局

    fill 和 expand

    from tkinter import *
    root1 = Tk()
    root2 = Tk()
    root3 = Tk()
    root4 = Tk()
    root1.geometry('260x260')
    root2.geometry('260x260')
    root3.geometry('260x260')
    root4.geometry('260x260')
    root1.title('ROOT 1')
    root2.title('ROOT 2')
    root3.title('ROOT 3')
    root4.title('ROOT 4')
    # ROOT1 窗口显示
    Label(root1,text='pack').pack()
    for i in range(5):
        Label(root1,text ='pack'+str(i)).pack()
    # ROOT2 窗口显示
    Label(root2,text='pack 11',bg='red').pack(fill=Y,expand = 1)
    Label(root2,text='pack 12',bg='blue').pack(fill=BOTH,expand = 1)
    Label(root2,text='pack 13',bg='green').pack(fill=X,expand =1)
    # ROOT3 窗口显示
    Label(root3,text='pack 31',bg='red', fg='yellow').pack(fill=Y,expand =0 , side = LEFT)
    Label(root3,text='pack 32',bg='blue').pack(fill=BOTH,expand = 0 , side = RIGHT)
    Label(root3,text='pack 33',bg='green').pack(fill=X,expand =0, side = TOP)
    Label(root3,text='pack 34',bg='green').pack(fill=X,expand =0, side = BOTTOM)
    Label(root3,text='pack 35',bg='green').pack(fill=X,expand =0, side = LEFT)
    # ROOT4 窗口显示
    Label(root4,text='pack 41',bg='red', fg='yellow').pack(fill=Y,expand =1 , side = LEFT)
    Label(root4,text='pack 42',bg='blue').pack(fill=BOTH,expand = 1 , side = RIGHT)
    Label(root4,text='pack 43',bg='green').pack(fill=X,expand =1, side = TOP)
    Label(root4,text='pack 44',bg='green').pack(fill=X,expand =1, side = BOTTOM)
    Label(root4,text='pack 45',bg='green').pack(fill=X,expand =1, side = LEFT)
    root1.mainloop()
    
    
    pack 布局示例图

    设置组件之间的间隙大小

    • ipadx,ipady设置内部间隙
    • padx,pady设置外部间隙
    • side 顺次放置控件
    # ipadx,ipady设置内部间隙
    # padx,pady设置外部间隙
    # side 顺次放置控件
    
    from tkinter import *
    root = Tk()
    root.geometry('300x300')
    root.title('Pack布局测试 2')
    
    lb_1 = Label(root,text='label_1',bg='red')
    lb_1.pack(side = LEFT, ipadx =10 , expand = 1)
    
    lb_2 = Label(root,text='label_2',bg='green')
    lb_2.pack(side = LEFT,padx = 10 , expand = 1, fill = BOTH)
    
    lb_3 = Label(root,text='label_3',bg='blue')
    lb_3.pack(side = LEFT, pady = 10 , expand = 1, fill = X)
    
    root.mainloop()
    
    
    label_1 的 ipadx 值变化效果图 label_2 的 padx 值变化效果图

    参考资料:

    Python的GUI编程之 Pack、Place、Grid 的区别

    相关文章

      网友评论

        本文标题:小鱼儿学Tkinter-Pack布局

        本文链接:https://www.haomeiwen.com/subject/exdovrtx.html