【问题标题】:How do you make a child label smaller than its parent frame?如何使子标签小于其父框架?
【发布时间】:2020-08-18 02:26:25
【问题描述】:

我的 GUI 中只有一帧,它会根据窗口大小调整自己的大小。框架有一个子标签,我希望标签始终是框架高度的 1/3 和框架宽度的 1/1.5。下面的代码尝试这样做,但标签总是将自身调整为框架的大小。

import tkinter

tk = tkinter.Tk()
tk.geometry("400x400")
f = tkinter.Frame(tk, bd=5, bg="white")
f.pack(padx=10, pady=10)

def callback(event):
    f.config(height=tk.winfo_height(), width=tk.winfo_width())
    l.config(width=int(f.winfo_width()/1.5), height=int(f.winfo_height()/3))
    
l = tkinter.Label(f, text="lead me lord", bg="yellow", relief=tkinter.RAISED, bd=5)
l.pack(side="bottom")

tk.bind("<Configure>", callback)
tk.mainloop()

【问题讨论】:

  • 这个标签是框架中唯一的东西,而框架是窗口中唯一的东西吗?通常,如果它是唯一的小部件与有许多其他小部件时,布局单个标签的方式会有所不同。我们可以告诉您如何实现您想要的,但是如果您计划添加其他小部件,那么除非我们知道窗口的总体计划,否则它可能只会产生其他问题。

标签: python tkinter tkinter-layout


【解决方案1】:

标签的宽度和高度以字符为单位。为了使用像素,您需要在标签中添加一个空图像:

img = tkinter.PhotoImage() # an image of size 0
l = tkinter.Label(f, text="lead me lord", bg="yellow", relief=tkinter.RAISED, bd=5,
                  image=img, compound='center')

其实在f.pack(...)中加上fill="both", expand=1就不需要在回调中调整frame了:

import tkinter

tk = tkinter.Tk()
tk.geometry("400x400")

f = tkinter.Frame(tk, bd=5, bg="white")
f.pack(padx=10, pady=10, fill="both", expand=1)

def callback(event):
    l.config(width=int(f.winfo_width()/1.5), height=int(f.winfo_height()/3))
    #l.config(width=event.width*2//3, height=event.height//3)  # same as above line if bind on frame

img = tkinter.PhotoImage()
l = tkinter.Label(f, text="lead me lord", bg="yellow", relief=tkinter.RAISED, bd=5,
                  image=img, compound='center')
l.pack(side="bottom")

f.bind("<Configure>", callback) # bind on frame instead of root window
tk.mainloop()

【讨论】:

    【解决方案2】:

    鉴于您的精确规格,最好的解决方案是使用place,因为它允许您使用相对宽度和高度。但是,如果您打算在窗口中添加其他小部件,place 很少是正确的选择。

    此示例将完全按照您的要求进行:将标签放在底部,高度为 1/3,宽度为 1/1.5。窗口大小改变时无需回调。

    注意:我必须将框架的调用更改为 pack。您的问题文本说它会扩展以填充窗口,但您的代码没有这样做。我添加了fillexpand 选项。

    import tkinter
    
    tk = tkinter.Tk()
    tk.geometry("400x400")
    f = tkinter.Frame(tk, bd=5, bg="white")
    f.pack(padx=10, pady=10, fill="both", expand=True)
    
    l = tkinter.Label(f, text="lead me lord", bg="yellow", relief=tkinter.RAISED, bd=5)
    l.place(relx=.5, rely=1.0, anchor="s", relheight=1/3., relwidth=1/1.5)
    
    tkinter.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      相关资源
      最近更新 更多