PYTHON:当我调用 canvas.bind 来监听键盘时,我在画布上绘制的内容意外地被清除了

问题描述 投票:0回答:0

我正在尝试使用此代码在背景上显示不断变化的图像:

from tkinter import *
from PIL import ImageTk, Image
from pynput import keyboard
import time


def DeclareVariable():

    # I create a background with a 0 displayed at the center
    fenetre = Tk()
    Background = ImageTk.PhotoImage(Image.open("Background.png"))
    BackgroundSize = Image.open("Background.png").size
    canvas = Canvas(fenetre, width=PITLayoutSize[0], height=BackgroundSize[1])
    canvas.pack()
    canvas.create_image(0, 0, anchor=NW, image=Background)
    canvas.create_image(130, 150, image=ImageTk.PhotoImage(Image.open("0.png")), tag="uniteTag")


def Main():
    global currentStage
    currentStage = 0
    global nbMovers
    nbMovers = 0

    def on_press(event):
        # When the user press 1 i increment a var and call load_image to update the number displayed on the background
        global currentStage
        if event.char == '1':
            currentStage = currentStage + 1
            print(currentStage)
            load_image()

    def load_image():
        # In this function i load the png with the right number depending on the value of the incremented var
        print(currentStage)
        unite = currentStage % 10
        etagePNG = "{}.png".format(unite)

        # I load the picture
        etageTK = ImageTk.PhotoImage(Image.open(etagePNG))
        etageC = canvas.find_withtag("uniteTag")
        if not etageC:
            print("Canvas introuvable ?!")
        else:
            # I update the item
            canvas.itemconfigure(etageC, image=etageTK)

        # I update the canvas
        canvas.update()

    # I bind my function to <Key> event
    canvas.bind("<Key>", on_press)

    # Focus on the canvas so he can receive keyboard event
    canvas.focus_set()

    # Start the main loop of the window
    fenetre.mainloop()

DeclareVariable()
Main()

想法是,当用户按下1时,

currentStage
应该增加,并绘制一个新图像来替换旧图像。我用
canvas.bind
来听按键。

然而,在

canvas.update
canvas.bind
之间的某个地方,图像似乎消失了。

如何确保在等待按键时仍然显示之前的号码?我无法使用

kynput
解决问题。我尝试在代码中添加
time.sleep
调用以尝试定位问题,但无法找出任何问题。

python canvas bind
© www.soinside.com 2019 - 2024. All rights reserved.