为什么宽度 tkinter 小部件与 tkinter 窗口不同 [英] Why width tkinter widgets are not the same as the tkinter window

查看:33
本文介绍了为什么宽度 tkinter 小部件与 tkinter 窗口不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想连续制作三个按钮,但小部件的宽度与 tkinter 窗口的宽度不同(希望每个按钮的宽度为 tkinter 窗口宽度(400 像素)的 1/3).

I want to make three buttons in a row, but the width of the widgets isnt the same factor as the tkinter window (wanted to have each button 1/3 width of the tkinter windows width(400px).

代码如下:

from tkinter import *

window = Tk()
window.geometry("400x400")
window.update()
print(window.winfo_width())
button = Button(window, width=window.winfo_width() // 3)
button.grid(row=0, column=0)
button = Button(window, width=window.winfo_width() // 3)
button.grid(row=0, column=1)
button = Button(window, width=window.winfo_width() // 3)
button.grid(row=0, column=2)

window.mainloop()

我该如何解决这个问题?提前致谢.

How can i solve this? Thanks in advance.

谢谢大家,我已经想通了.如果其他人有同样的问题,这个网站也可能会有所帮助.

Thanks everyone i have figured it out. If someone else has the same problem, this site might also help.

推荐答案

除非你指定了图片,否则按钮的宽度是以字符数指定的,而不是像素数.

Unless you'ver specified images, the width of a button is specified in the number of characters, not the number of pixels.

有更好的方法来确保每个按钮都占窗口的 1/3.由于您使用的是网格,因此您可以使用 uniform 选项强制列的大小相等.只需为每一列将其设置为相同的字符串,并为每一列赋予一个非零权重,以便它们在有额外空间时同样增长.

There are better ways to make sure each button is 1/3 of the window. Since you're using grid, you can force the columns to be equal in size using the uniform option. Just set it to the same string for every column, and give every column a non-zero weight so that they grow equally if there's extra space.

注意:当窗口的所有布局代码组合在一起而不是与其他代码交错时,我发现解决布局问题要容易得多,所以我就是这样构建这个示例的.

Note: I find it much easier to solve layout problems when all of the layout code for a window is grouped together instead of interleaved with other code, so that's how I've structured this example.

from tkinter import *

window = Tk()
window.geometry("400x400")
window.update()
print(window.winfo_width())

window.grid_columnconfigure((0,1,2), uniform="equal", weight=1)

button1 = Button(window)
button2 = Button(window)
button3 = Button(window)

button1.grid(row=0, column=0, sticky="ew")
button2.grid(row=0, column=1, sticky="ew")
button3.grid(row=0, column=2, sticky="ew")

window.mainloop()

这篇关于为什么宽度 tkinter 小部件与 tkinter 窗口不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆