简体   繁体   English

Tkinter窗口无法打开

[英]Tkinter window not opening

I was trying to create a simple moving block using tkinter in Python 3, and everything was working until I imported time. 我试图在Python 3中使用tkinter创建一个简单的移动块,并且一切正常,直到导入时间。 The window now won't open. 现在该窗口将不会打开。 I've tried removing the import, and it doesn't help. 我尝试删除导入,但没有帮助。 This is my code: 这是我的代码:

from tkinter import *
import time

canvas_height = 400
canvas_width = 600
canvas_colour = "grey50"
moveBoolean = "True"

def move():
    global moveBoolean
    while moveBoolean == "True":
        time.sleep(0.005)
        canvas.move(square, 90, 90)
        time.sleep(0.005)
        canvas.move(square, 180, 180)
        time.sleep(0.005)
        canvas.move(square, 50, 100)

window = Tk()

canvas = Canvas(bg=canvas_colour, height=canvas_height, width=canvas_width, highlightthickness=0)
canvas.pack()

square = canvas.create_rectangle(50, 50, 50, 50, width=50, fill="black")

move()

window.mainloop()

These problems are generally solved with the use of classes, which you should learn and use before coding GUIs IMHO. 这些问题通常可以通过使用类来解决,在编写GUI恕我直言之前,您应该学习并使用这些类。 You should not use time() as it can interrupt the infinite Tkinter loop. 您不应该使用time(),因为它会中断无限的Tkinter循环。 Use Tkinter's after() instead. 请改用Tkinter的after()。 Also, you never set moveBoolean to False, so the while statement runs until the program is cancelled, and the second time through the square will be off the canvas, which is why you don't get anything visible. 另外,您永远不会将moveBoolean设置为False,因此while语句将运行直到程序被取消为止,并且第二次通过该方框将不在画布上,这就是为什么您看不到任何东西的原因。 The following solves your problems but again would be better if a class structure were used. 以下内容解决了您的问题,但是如果使用类结构,它也会更好。

from tkinter import *
from functools import partial

canvas_height = 400
canvas_width = 600
canvas_colour = "grey50"
moveBoolean = "True"

def move_it(ctr=0):
    if ctr < len(coords):
        x, y = coords[ctr]
        ctr += 1
        print ctr, x, y
        canvas.move(square, x, y)
        window.after(1000, partial(move_it, ctr))

window = Tk()

canvas = Canvas(bg=canvas_colour, height=canvas_height,
         width=canvas_width, highlightthickness=0)
canvas.pack()

square = canvas.create_rectangle(50, 50, 50, 50, width=50, fill="black")

coords = ((90, 90),
          (180, 180),
          (50, 50))
move_it()

window.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM