如何使用gridManager使.grid\u columnconfigure()在框架内工作?

2024-04-19 18:28:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经问过这个问题,但得到的答案只有包经理

我想在python中使用grid方法和grid\u columnconfigure/grid\u rowconfigure创建一个带有tkinter的GUI。不幸的是,这在框架内不起作用

from tkinter import *

master = Tk()
master.state('zoomed')
f = Frame(master, width=800, height=400)

Label1 = Label(f, text='Label 1')
Label2 = Label(f, text='Label 2')

f.grid_columnconfigure(0, weight=1)
f.grid_columnconfigure(2, weight=1)
f.grid_columnconfigure(4, weight=1)

Label1.grid(row=0, column=1)
Label2.grid(row=0, column=3)

master.grid_rowconfigure(0, weight=1)
master.grid_rowconfigure(2, weight=1)
master.grid_columnconfigure(0, weight=1)
master.grid_columnconfigure(2, weight=1)
f.grid(row=1, column=1)

master.mainloop()

我希望两个标签之间有空间,但这是行不通的,因为框架没有占用更多的空间内掌握。我该怎么做


Tags: 答案textmaster框架tkinter空间columnlabel
1条回答
网友
1楼 · 发布于 2024-04-19 18:28:12

这对我来说很有用,但是使用pack()会更容易


框架大小不会更改为标签大小:

f.grid_propagate(False)

框架所在的列和行将使用所有空间(因为没有其他列和行)

master.grid_rowconfigure(1, weight=1)
master.grid_columnconfigure(1, weight=1)

框架将调整为列和行大小(已使用窗口中的所有空间)

f.grid(..., sticky='news')

为了测试代码,我添加了背景色-它显示了小部件的实际大小


代码:

from tkinter import *

master = Tk()
master['bg'] = 'red'

master.grid_rowconfigure(1, weight=1)
master.grid_columnconfigure(1, weight=1)

f = Frame(master, width=400, height=300)
f.grid(row=1, column=1, sticky='news')

f.grid_propagate(False)

f.grid_columnconfigure(0, weight=1)
f.grid_columnconfigure(2, weight=1)
f.grid_columnconfigure(4, weight=1)

l1 = Label(f, text='Label 1', bg='green')
l2 = Label(f, text='Label 2', bg='green')

l1.grid(row=0, column=1)
l2.grid(row=0, column=3)

master.mainloop()

如果删除width=400, height=300,那么窗口在开始时将没有大小

相关问题 更多 >