Python tkinter画布保持最小化
如何让画布实际有一个尺寸Python tkinter画布保持最小化,python,tkinter,Python,Tkinter,如何让画布实际有一个尺寸 root = Tk() canv = Canvas(root, width=600, height=600) canv.pack(fill = BOTH, expand = True) root.after(1, draw) mainloop() 只需在左上角创建一个具有1px画布的窗口 编辑:我省略了绘图,因为它没有抛出任何东西,因此看起来不相关。但是,如果我通过pdb浏览它,它会运行得非常完美,下面是完整的代码: from tkinter import * fr
root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)
root.after(1, draw)
mainloop()
只需在左上角创建一个具有1px画布的窗口
编辑:我省略了绘图,因为它没有抛出任何东西,因此看起来不相关。但是,如果我通过pdb浏览它,它会运行得非常完美,下面是完整的代码:
from tkinter import *
from pdb import set_trace
class Field: #abstact
def __init__(self, size):
super().__init__()
self.tiles = [[(None, 0) for i in range(size[1])] for j in range(size[0])] #list of columns
def get_tile(self, x,y):
return tiles[x][y]
def inc_tile(self, x,y,player):
t = self.tiles[x][y]
tiles[x][y] = (player, t[1])
class RectField(Field):
def __init__(self, size):
super().__init__(size)
def select_tile(self, x, y):
lx = len(self.tiles)
rx = floor(x*lx)
ly = len(self.tiles[rx])
ry = floor(x*ly)
return (rx, ry)
def draw(self, canvas):
canvas.delete(ALL)
w = canvas.winfo_width()
h = canvas.winfo_height()
canvas.create_rectangle(0, 0, w, h, fill='#f0f')
sx = w/len(self.tiles)
for i in range(len(self.tiles)):
sy = h/len(self.tiles[i])
for j in range(len(self.tiles[i])):
pl = self.tiles[i][j][0]
cl = '#888' if not pl else ('#f20' if pl == 1 else '#02f')
canvas.create_rectangle(i*sx, j*sy, (i+1)*sx, (j+1)*sy, fill=cl, outline='#000')
############################################################################## #####################
# MAIN
############################################################################## #####################
root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)
#set_trace()
field = RectField((4,4))
def init():
canv.create_rectangle(0, 0, 600, 600, fill='#f0f')
set_trace()
field.draw(canv)
root.update()
root.after(1, init)
mainloop()
操作系统是ubuntu 16.04,
python版本是预先安装的python3,通过终端运行我能够让您的画布显示并正常工作。看起来问题出在
init
函数上。调用init()函数时不需要定义等待时间,只需直接调用它,程序就会完成其余的工作
另外,我已经查看了canvas的tkinter文档,没有看到类似于.draw()
的任何内容,我认为tkinter不存在类似的函数。我可能错了,但如果它确实存在,文档就不明显了
改用这个:
def init():
canv.create_rectangle(0, 0, 600, 600, fill='blue')
# I only changed the color to make sure it was working
#set_trace() # not needed.
#field.draw(canv) # does nothing?
#root.update() # not needed in this case.
init()
您的画布没有保持最小化。如果你给画布一个独特的背景色,你会发现它会立即填满整个窗口,并保持这种状态 您得到的窗口宽度和高度为
1
,因为您没有给tkinter足够的时间在要求尺寸之前绘制它winfo_width
和winfo_height
返回实际高度,在窗口在屏幕上实际可见之前,无法计算实际高度
最简单的解决方案是在调用init
函数之前强制更新。您可以通过调用update
然后调用init
而不是在之后使用,来完成此操作
与此相反:
root.after(1, init)
这样做:
root.update()
init()
不能复制。这扇窗户应该是600x600大。还有,draw
在做什么?这与问题有关吗?显然,我没有使用它进行测试,它在Python 3.6.0和2.6.6上,在Debian的派生版本上,使用KDE作为窗口管理器,运行良好。您是直接在终端中运行它,还是通过空闲(或其他IDE)运行它?chagngecanv.pack(fill=BOTH,expand=True)
到canv.grid()
画布将显示,但不会调整大小。grid不会更改任何内容您不需要root.after(1,init)
只需执行init()
您还应该执行root.mainloop()
而不仅仅是mainloop()