【发布时间】:2020-04-14 02:36:21
【问题描述】:
我制作了一个简单的“游戏 9”,它在纯 Python 中运行良好。现在我想在 Tkinter 窗口中做同样的事情。 我正在尝试通过按键刷新 Tkinter 窗口 - 当我按下数字 (1-8) 时,我将矩阵设置为不同的数字,我想刷新窗口。不幸的是,我不知道如何做好。我使用了 window.update() 和 window.destroy() 但这个解决方案很糟糕。您能否帮助如何在不使用 window.destroy() 的情况下刷新我的 Tkinter 窗口? 我是 Tkinter 和 Python 的新手 :)
import random
import tkinter as tk
from time import sleep
import keyboard
x,px,py,px2,py2 = 0,0,0,0,0
matrix = [[0,0,0],[0,0,0],[0,0,0]]
# generate 9 unique numbers (0 to 8) and insert them into matrix
z = random.sample(range(0,9),9)
matrix[0] = [(z[0]), (z[1]), (z[2])]
matrix[1] = [(z[3]), (z[4]), (z[5])]
matrix[2] = [(z[6]), (z[7]), (z[8])]
def printmatrix():
label1 = tk.Label(text = matrix[0])
label1.grid(column = 1, row = 1)
label2 = tk.Label(text = matrix[1])
label2.grid(column = 1, row = 2)
label3 = tk.Label(text = matrix[2])
label3.grid(column = 1, row = 3)
# check win
def check_win():
if matrix[0] == [1,2,3] and matrix[1] == [4,5,6] and matrix[2] == [7,8,0]:
label4 = tk.Label(text = "you won !!!")
label4.grid(column = 0, row = 6)
window.update()
sleep (5)
exit ()
while __name__ == '__main__':
window = tk.Tk()
window.title("GAME 9")
window.geometry("300x300")
printmatrix()
window.update()
check_win()
# read key 1-8
if keyboard.read_key() == "1":
x = 1
if keyboard.read_key() == "2":
x = 2
if keyboard.read_key() == "3":
x = 3
if keyboard.read_key() == "4":
x = 4
if keyboard.read_key() == "5":
x = 5
if keyboard.read_key() == "6":
x = 6
if keyboard.read_key() == "7":
x = 7
if keyboard.read_key() == "8":
x = 8
# check position of "0"
for pozx,j in enumerate(matrix):
for pozy,l in enumerate(j):
if l==0:
px = int(pozx)
py = int(pozy)
# check position of moved number
for pozx2,j in enumerate(matrix):
for pozy2,l in enumerate(j):
if l==x:
px2 = int(pozx2)
py2 = int(pozy2)
# check if the moved number is on the right place (if we can use it)
if (px == px2 or py == py2) and ((py+1 or py-1 == py2) or (px+1 or px-1 == px2)):
if (px == 0 and px2 == 1) or (px == 1 and px2 == 2) or (px == 1 and px2 == 0) or (px == 2 and px2 == 1) or (py == 0 and py2 == 1) or (py == 1 and py2 == 2) or (py == 1 and py2 == 0) or (py == 2 and py2 == 1):
matrix[px2][py2] = 0
matrix[px][py] = x
printmatrix()
else:
label5 = tk.Label(text = "wrong move, try again")
label5.grid(column = 0, row = 5)
window.update()
sleep(2)
printmatrix()
else:
label6 = tk.Label(text = "wrong move, try again")
label6.grid(column = 0, row = 4)
window.update()
sleep(2)
printmatrix()
window.destroy()
window.mainloop()
【问题讨论】:
-
不要使用模块
keyboard但tkinter方法将函数绑定到按下的键 -root.bind("1", function_name)并在此函数内部设置变量。您将必须了解所有 GUI 框架的工作原理并重写它。 -
在开始时创建所有标签,之后只更改标签中的文本。不要在同一个地方一遍又一遍地创建标签,因为之前的标签仍在窗口中并占用内存。