Tkinter grid and widget size

时间:2019-01-09 21:45:57

标签: python tkinter

I am actually learning Tkinter and I want to do a window looking like this (tetris GUI) : image So I want to do a 20x15 grid (h x w) with a tile size of 25px (so 500px x 375px playArea size) So here is the code I made :

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

I use HEIGHT and WIDTH variables to define the size of my canvas and my TILE_SIZE variable to define te amount of tile is needed (to configure columnspan and rowspan) my first problem is that my :

print(playarea.grid_size())

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

Then the other one issue is with my buttons, here I created two buttons (newGame and test), I want the newGame to be 75px wide (or 3 * TILE_SIZE) but when I run it (for both of width = 75 and width = 3 * TILE_SIZE) the

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.

1 个答案:

答案 0 :(得分:0)

  

print(playarea.grid_size())

     

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

不。 grid_size返回网格的大小(行和列数)。根据官方的tcl / tk文档,这就是计算值的方式:

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

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

  

print(newGameButton.winfo_width())

     

返回我617像素,按钮很大,我不明白为什么,有人可以解释网格的工作原理吗?是什么原因造成的。

创建带有文本但没有图像的按钮时,width被解释为许多字符而不是 pixels