我试图在Tkinter制作一个简单的俄罗斯方块游戏,但实际的窗口不会打开。如果我不使用time()函数使游戏片段掉落,它将绘制,但是一旦我添加time()函数,窗口就会消失。我可以看到该程序正在通过打印掉落片的坐标来工作,但是我的代码的下降方面似乎干扰了tkinter窗口的绘制。
为什么程序没有画出窗口?
from tkinter import *
from tkinter import ttk
import random
import time
root = Tk()
root.title('Emblas tetris game')
x_init = root.winfo_pointerx()
y_init = root.winfo_pointery()
WIDTH = root.winfo_screenwidth()
HEIGHT = root.winfo_screenheight()
basicbox = Canvas(root, width=WIDTH, height=HEIGHT)
basicbox.pack()
gameboard = basicbox.create_rectangle(WIDTH/6, 0, WIDTH * 0.84, 720,
outline='gray', fill='white', width=4)
#------- FIGURES -------------------------------------------
def countpointsinfig(): #redraws each figure as it is falling, updating all coordinates
global x0, y0, x1, y1, x2, y2, x3, y3
numpoints = len(points)
if numpoints == 8:
x0, y0, x1, y1, x2, y2, x3, y3 = basicbox.coords(drawshape)
print(x0, y0, x1, y1, x2, y2, x3, y3)
def I_shape():
global drawshape, points
points = [WIDTH/2 - 10, 0,#0
WIDTH/2 + 10, 0,#1
WIDTH/2 + 10, 80,#2
WIDTH/2 - 10, 80,#3
]
drawshape = basicbox.create_polygon(points, outline='yellow', fill='yellow')
def O_shape():
global drawshape, points
points = [WIDTH/2 - 20, 0,#0
WIDTH/2 + 20, 0,#1
WIDTH/2 + 20, 40,#2
WIDTH/2 - 20, 40,#3
]
drawshape = basicbox.create_polygon(points, outline='red', fill='red')
#--------- GAME -----------------------------------------------
def startgame():
global rand_shape, pickone
pickone = [I_shape, O_shape]
rand_shape = random.choice(pickone)()
autofall = True #very very VERY interesting....... This is the problem. This function should move my tetris piece down. If i remove this bit the code works. Why?
while autofall:
time.sleep(1)
basicbox.move(drawshape, 0, 20)
countpointsinfig()
#----------- MOVE FIGURES -----------------------
def leftmove(event):
countpointsinfig()
basicbox.move(drawshape, -20, 0)
def rightmove(event):
countpointsinfig()
basicbox.move(drawshape, 20, 0)
def downmove(event):
countpointsinfig()
basicbox.move(drawshape, 0, 20)
root.bind('<Left>', leftmove)
root.bind('<Right>', rightmove)
root.bind('<Up>', upmove)
root.bind('<Down>', downmove)
#----------------------------------------------------------------
startgame()
root.mainloop()
答案 0 :(得分:1)
root.mainloop()
while autofall
是问题所在。
在this other post中,您可以了解mainloop()
的作用。
解决问题的简便方法是使用after()
方法。
更改此代码:
def startgame():
global rand_shape, pickone
pickone = [I_shape, O_shape]
rand_shape = random.choice(pickone)()
autofall = True
while autofall:
time.sleep(1)
basicbox.move(drawshape, 0, 20)
countpointsinfig()
为此:
def startgame():
global rand_shape, pickone
pickone = [I_shape, O_shape]
rand_shape = random.choice(pickone)()
autofall()
def autofall():
basicbox.move(drawshape, 0, 20)
countpointsinfig()
basicbox.after(1000,autofall)