from tkinter import *
import time
alien = Tk()
alien.title("Alien")
c = Canvas(alien, height=300, width=400)
c.pack()
body = c.create_oval(100, 150, 300, 250, fill="green")
eye = c.create_oval(170, 70, 230, 130, fill="white")
eyeball = c.create_oval(190, 90, 210, 110, fill="black")
mouth = c.create_oval(150, 220, 250, 240, fill="red")
neck = c.create_line(200, 150, 200, 130)
hat = c.create_polygon(180, 75, 220, 75, 200, 20, fill="blue")
def mouth_open():
c.itemconfig(mouth, fill="black")
def mouth_close():
c.itemconfig(mouth, fill="red")
def blink():
c.itemconfig(eye, fill="green")
c.itemconfig(eyeball, state=HIDDEN)
def unblink():
c.itemconfig(eye, fill="white")
c.itemconfig(eyeball, state=NORMAL)
def steal_hat():
c.itemconfig(hat, state=HIDDEN)
c.itemconfig(words, text="GIVE ME MY HAT BACK")
def burp():
mouth_open()
c.itemconfig(words, text="Burp!!!")
time.sleep(1)
c.itemconfig(words, text="I'm an alien!")
mouth_close()
def blink2():
blink()
time.sleep(1)
unblink()
def eye_control(event):
key = event.keysym
if key == "Up":
c.move(eyeball, 0, -1)
elif key == "Down":
c.move(eyeball, 0, 1)
elif key == "Left":
c.move(eyeball, -1, 0)
elif key == "Right":
c.move(eyeball, 1, 0)
c.bind_all('<Key>', eye_control)
words = c.create_text(200, 280, text="I'm an alien!")
window = Tk()
window.title("Options")
btnBlink = Button(window, text="blink", command=blink2)
btnBlink.pack()
alien.mainloop()
window.mainloop()
我做了一个外星人,我想让用户能够偷走外星人的帽子,让外星人打嗝,让外星人眨眼,并能够移动外星人的眼球。到目前为止,我已经能够控制他的眼球,但眨眼无法正常工作。我已经在blink2的定义中删除了time.sleep(1),但这并没有真正改变任何东西。 我如何让外星人能够眨眼。非常感谢任何帮助。
答案 0 :(得分:0)
在你的函数blink2
中,它永远不会要求刷新画布,所以你的外星人似乎永远不会眨眼。
您可以通过删除time.sleep(1)
并使用after
代替时间来解决此问题。
要实现这一点,blink2
可能如下所示:
def blink2():
blink()
window.after(1000, unblink) # Timing is in milliseconds.
请注意,使用root
作为Tk()
的参考通常也是惯例。