gpt4 book ai didi

python - Tkinter 网格和小部件大小

转载 作者:太空宇宙 更新时间:2023-11-03 21:22:39 24 4
gpt4 key购买 nike

我实际上正在学习 Tkinter,我想做一个看起来像这样的窗口(俄罗斯方 block GUI): image所以我想做一个 20x15 网格(高 x 宽),图 block 大小为 25 像素(因此游戏区域大小为 500 像素 x 375 像素)这是我编写的代码:

from tkinter import *
from random import randint

root = Tk()
root.resizable(False, False)

# PLAYAREA SIZE
HEIGHT = 500
WIDTH = HEIGHT // 2
TILE_SIZE = 25

playarea = Canvas(root, width=WIDTH, height=HEIGHT, bg='yellow')
playarea.grid(column=6, row=0, columnspan=WIDTH // TILE_SIZE, rowspan=HEIGHT // TILE_SIZE)


menuFrame=Frame(root, width=(WIDTH // 2), height=HEIGHT).grid(column=0, row=0, columnspan= (WIDTH // 2) // TILE_SIZE , rowspan= int(HEIGHT / TILE_SIZE))
newGameButton = Button(menuFrame, text='Start', width= 75 , height = 1 * TILE_SIZE)
newGameButton.grid(column=1, row=1,columnspan=3, rowspan= 1)
newTestButton = Button(menuFrame, text='Test', width= 5 * TILE_SIZE, height = 1* TILE_SIZE)
newTestButton.grid(column=0, row=2, columnspan=5, rowspan=1)
root.update()

print(newGameButton.winfo_width())
print(playarea.grid_size())
#print(playarea.grid_info())

root.mainloop()

我使用 HEIGHT 和 WIDTH 变量来定义 Canvas 的大小,使用 TILE_SIZE 变量来定义需要的图 block 数量(配置列跨度行跨度)第一个问题是我的:

print(playarea.grid_size())

返回 (0,0),因为我配置了 columnspan 和 rowspan 它应该返回我 (10,20),不是吗?

然后另一个问题是我的按钮,在这里我创建了两个按钮(newGame 和 test),我希望 newGame 的宽度为 75px(或 3 * TILE_SIZE),但是当我运行它时(宽度都 = 75)且宽度 = 3 * TILE_SIZE)

print(newGameButton.winfo_width())

返回我617px,按钮很大,我不明白为什么,有人可以解释一下网格是如何工作的吗?这是什么原因造成的。

最佳答案

print(playarea.grid_size())

Return (0,0), as I configured columnspan and rowspan it should return me (10,20), no ?

没有。 grid_size 返回网格的大小(行数和列数)。根据官方 tcl/tk 文档,这是如何计算该值的:

“大小由占据最大行或列的从属设备确定,或者由最小大小、权重或填充不为零的最大列或行确定。”

在您的具体情况下,您仅将小部件放在第 0 行第 0 列中,因此报告的 (0,0) 大小是正确的。

print(newGameButton.winfo_width())

Return me 617px and the button is huge, I don't understand why, can someone explain how grid works ? What's causing this.

当您创建一个包含文本但没有图像的按钮时,宽度将被解释为字符数,而不是像素

关于python - Tkinter 网格和小部件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54118832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com