簡體   English   中英

在 Python 中刷新 Tkinter 窗口

[英]refresh Tkinter window in Python

我做了一個簡單的“游戲 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()

我沒有對它進行最后的測試,但它使用了大多數 GUI 中使用的方法。

它將功能綁定/分配給鍵,以便運行move(number)和移動編號。

它在開始時創建標簽,稍后僅更改標簽中的文本。

它不需要任何update因為它會自動更新。

順便說一句:就像在數學中使用的矩陣一樣,我使用[row][column]這意味着[y][x] ,而不是[x][y]

import random
import tkinter as tk
import time

# generate 9 unique numbers (0 to 8) and insert them into matrix 
z = random.sample(range(0,9),9)

matrix = [
    [(z[0]), (z[1]), (z[2])],
    [(z[3]), (z[4]), (z[5])],
    [(z[6]), (z[7]), (z[8])],
]    
#print(matrix)

def update_labels():
    for row_matrix, row_labels in zip(matrix, labels):
        for item, label in zip(row_matrix, row_labels): 
            label["text"] = item


def move(number):
    #print(number)

    # find position of "0" and moved number
    for y, row in enumerate(matrix):
        for x, cell in enumerate(row):
            if cell == 0:
                zero_x = x
                zero_y = y
            elif cell == number:
                number_x = x
                number_y = y

    # check if the moved number is on the right place  (if we can use it)
    diff_x = abs(zero_x - number_x)
    diff_y = abs(zero_y - number_y)
    if (diff_x == 0 and diff_y == 1) or (diff_x == 1 and diff_y == 0):
            matrix[number_y][number_x] = 0
            matrix[zero_y][zero_x] = number
    else:
        message_label['text'] = "wrong move, try again"

    update_labels()
    check_win()

def check_win():
    if matrix == [[1,2,3], [4,5,6], [7,8,0]]:
        message_label['text'] = "you won !!!"
        time.sleep(5)
        exit()

if __name__ == '__main__':
    window = tk.Tk()
    window.title("GAME 9")
    window.geometry("300x300")

    # create labels
    labels = []
    for y in range(1, 4):
        row = []
        for x in range(1, 4): 
            label = tk.Label(window)
            label.grid(column=x, row=y)
            row.append(label)
        labels.append(row)

    # label for messages        
    message_label = tk.Label(window)
    message_label.grid(column=0, row=4, columnspan=5)

    # fill labels at start
    update_labels()

    # bind keys to function
    for i in range(1, 10):
        window.bind(str(i), lambda event, x=i:move(x))

    # start program and show window
    window.mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM