问题
So, I know about the sleep function, but it doesn't work how I expected it to work. If I do something like this:
from time import sleep
print('Something')
sleep (10)
print('Something')
It works how (I think) it should (it prints one thing, waits and then prints the other one).
But in my code it doesn't work like that. This is the whole code:
from tkinter import *
from time import sleep
# Fenster
window = Tk()
window.title('Test')
c = Canvas(window, height=450, width=800)
c.pack()
# Bildelemente
Hintergrund = PhotoImage(file='Hintergrund.gif')
Background = Label(image=Hintergrund)
Background.image = Hintergrund
Background.place(x=0, y=0)
Boden = PhotoImage(file='Boden.gif')
Ground = Label(image=Boden)
Ground.image = Boden
Ground.place(x=0, y=300)
Char = PhotoImage(file='Char.gif')
Character = Label(image=Char)
Character.image = Char
Character.pack()
# Koordinaten ermitteln
def coordinatesX(id_num):
pos = c.coords(id_num)
x = (pos[0] + pos[2])/2
return x
def coordinatesY(id_num):
pos = c.coords(id_num)
y = (pos[1] + pos[3])/2
return y
# Charakter bewegen
def Char_move(event):
if event.keysym == 'Right' and coordinatesX(Char_) < 800 - 50:
c.move(Char_, 10, 0)
Character.place(x=(coordinatesX(Char_)), y=(coordinatesY(Char_)))
if event.keysym == 'Left' and coordinatesX(Char_) > 0:
c.move(Char_, -10, 0)
Character.place(x=(coordinatesX(Char_)), y=(coordinatesY(Char_)))
if event.keysym == 'Up' and coordinatesY(Char_) < 300 and coordinatesY(Char_) > 0:
jump()
sleep(5)
print('NA')
c.bind_all('<Key>', Char_move)
def jump():
c.move(Char_, 0, -50)
Character.place(x=(coordinatesX(Char_)), y=(coordinatesY(Char_)))
# Objekt zur Postitionsbestimmung vom Charakter
Char_ = c.create_oval(0, 0, 50, 50, fill='red')
c.move(Char_, 100, 223)
Character.place(x=(coordinatesX(Char_)), y=(coordinatesY(Char_)))
In this part I want it to wait and then do something (in this "example" print):
jump()
sleep(5)
print('NA')
But when I run the program and hit 'Up', it waits and then the object goes up and the program prints "NA" at the same time. How do I have to do this so that the object goes up, it waits and then prints something?
回答1:
Do not use sleep. Use the tkinter after method instead.
jump()
window.after(5000, lambda x: print('NA'))
Sleep freezes your gui. Jump is executed but sleep prevents the gui from being redrawn, therefore you do not see any change. After is a method from Tk and allows you to schedule operations.
来源:https://stackoverflow.com/questions/42651018/how-can-i-use-sleep-properly