gpt4 book ai didi

python - 动画 Tkinter

转载 作者:太空宇宙 更新时间:2023-11-03 14:28:05 25 4
gpt4 key购买 nike

我正在尝试编写一个基本的 tkinter 示例,该示例将显示一个横跨框架的框。此时下面的代码只会打印最终结果,并不会显示方 block 移动。我如何修复代码,以便它可以随着时间的推移工作而无需使用诸如移动之类的东西,以便我可以在以后随着时间的推移修改形状?

from tkinter import Tk, Canvas, Frame, BOTH
from time import sleep


class Example(Frame):

def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.parent.title("Board")
self.pack(fill=BOTH, expand=1)
self.canvas = Canvas(self)
self.ctr = 10
self.initUI()


def initUI(self):
print(self.ctr)
#The first four parameters are the x,y coordinates of the two bounding points.
#The top-left and the bottom-right.
r = self.canvas.create_rectangle((self.ctr * 10), 0, (self.ctr * 10 + 50), 50,
outline="#fb0", fill="#fb0")
'''
canvas.create_rectangle(50, 0, 100, 50,
outline="#f50", fill="#f50")
canvas.create_rectangle(100, 0, 150, 50,
outline="#05f", fill="#05f")
'''
self.canvas.pack(fill=BOTH, expand=1)

if self.ctr > 0:
self.updateUI()

def updateUI(self):
self.ctr -= 1
sleep(1)
self.initUI()



def main():

root = Tk()
root.geometry("400x100+300+300")
ex = Example(root)
root.mainloop()


if __name__ == '__main__':
main()

最佳答案

这应该让你走到了一半(你需要修复缩进,偏移量不正确并且计数器不会重置)。将来,请确保在使用 GUI 的事件循环时不要调用 sleep 。大多数 GUI 都有一种方法可以将某些东西挂接到它们的事件循环中(在本例中为 root.after 调用)。我所做的只是让您的代码部分工作 - 这不应被视为惯用 python 的指示。

from tkinter import Tk, Canvas, Frame, BOTH
from time import sleep

class Example(Frame):

def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.parent.title("Board")
self.pack(fill=BOTH, expand=1)
self.canvas = Canvas(self)
self.ctr = 10


def initUI(self):
print(self.ctr)
#The first four parameters are the x,y coordinates of the two bounding points.
#The top-left and the bottom-right.
r = self.canvas.create_rectangle((self.ctr * 10), 0, (self.ctr * 10 + 50), 50,
outline="#fb0", fill="#fb0")
'''
canvas.create_rectangle(50, 0, 100, 50,
outline="#f50", fill="#f50")
canvas.create_rectangle(100, 0, 150, 50,
outline="#05f", fill="#05f")
'''
self.canvas.pack(fill=BOTH, expand=1)

self.ctr += 1
if self.ctr > 0:
self.parent.after(1000, self.initUI)

def main():

root = Tk()
ex = Example(root)
root.geometry("400x100+300+300")
root.after(1000, ex.initUI)
root.mainloop()

if __name__ == '__main__':
main()

关于python - 动画 Tkinter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16824581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com