微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使子标签小于其父框架?

如何解决如何使子标签小于其父框架?

我的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()

解决方法

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

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')

实际上,如果您将fill="both",expand=1添加到f.pack(...)中,则无需在回调中调整框架的大小:

import tkinter

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

f = tkinter.Frame(tk,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,compound='center')
l.pack(side="bottom")

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

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

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

注意:我必须将该帧的呼叫更改为pack。您的问题文本说它将扩展以填充窗口,但您所执行的代码没有这样做。我添加了fillexpand选项。

import tkinter

tk = tkinter.Tk()
tk.geometry("400x400")
f = tkinter.Frame(tk,expand=True)

l = tkinter.Label(f,bd=5)
l.place(relx=.5,rely=1.0,anchor="s",relheight=1/3.,relwidth=1/1.5)

tkinter.mainloop()

screenshot of window

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。