【问题标题】:Adding padding to a tkinter widget only on one side仅在一侧向 tkinter 小部件添加填充
【发布时间】:2011-05-09 15:25:40
【问题描述】:

如何在没有 tkinter 居中小部件的情况下向 tkinter 窗口添加填充? 我试过了:

 self.canvas_l = Label(self.master, text="choose a color:", font="helvetica 12")
 self.canvas_l.grid(row=9, column=1, sticky=S, ipady=30)

 self.canvas_l = Label(self.master, text="choose a color:", font="helvetica 12")
 self.canvas_l.grid(row=9, column=1, rowspan=2, sticky=S, pady=30)

我只希望标签顶部有 30 像素的内边距。

【问题讨论】:

    标签: python tkinter padding


    【解决方案1】:

    gridpack 方法的填充选项 padxpady 可以采用代表左/右和上/下填充的 2 元组

    这是一个例子:

    import tkinter as tk
    
    class MyApp():
        def __init__(self):
            self.root = tk.Tk()
            l1 = tk.Label(self.root, text="Hello")
            l2 = tk.Label(self.root, text="World")
            l1.grid(row=0, column=0, padx=(100, 10))
            l2.grid(row=1, column=0, padx=(10, 100)) 
    
    app = MyApp()
    app.root.mainloop()
    

    【讨论】:

    • 有趣。这种行为是否在任何半官方的地方描述过?我最喜欢的两个 tk 资源,effbotNew Mexico Tech,并没有暗示这种方式填充可能不均匀。秘密的无证行为?
    • @Kevin:tkinter 只是一个包含 tk 库的嵌入式 tcl 解释器的 pythonic 包装器。 tk 的规范文档提到了这个特性。这是参考:tcl.tk/man/tcl8.5/TkCmd/grid.htm#M16
    • 适用于 Grid padx/pady,但不适用于 Frame。可能还有更多例外
    • @DanielBraun:它也适用于框架。 Tkinter 不在乎它是什么类型的小部件。
    • @Giova:是的,元组版本仅适用于gridpackpadxpady 选项。某些小部件的padxpady 选项不同。您不能将它用于小部件的padxpady 选项。我会尽量澄清我的答案。
    【解决方案2】:

    有多种方法可以使用placegrid 甚至pack 方法。

    示例代码:

    from tkinter import *
    root = Tk()
    
    l = Label(root, text="hello" )
    l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
    # well you can also use side=LEFT inside the pack method of the label widget.
    

    要根据列和行放置小部件,请使用网格方法:

    but = Button(root, text="hello" )
    but.grid(row=0, column=1)
    

    【讨论】:

      【解决方案3】:
      -pady {10,0}
      

      这样,您将顶部的填充称为 10,将下方的填充称为 0。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-06
        • 2021-09-15
        • 2022-12-03
        • 1970-01-01
        相关资源
        最近更新 更多