2 回答

TA贡献1982条经验 获得超2个赞
您可以通过它,但是您正在丢弃价值。另外,Hero不应该继承自mainWindow.
您需要另存world为属性,以便以后可以引用它。
class Hero():
def __init__(self,world):
self.world = world
...
然后,您可以使用self.world来引用画布:
def moveHeroBody():
print("moveHeroBody")
self.world.delete(heroBody)
虽然,上面的代码会失败,因为heroBody它是一个局部变量__init__- 你需要对它做同样的事情:
class Hero():
def __init__(self,world):
self.world = world
...
self.heroBody = world.create_oval(...)
#Move the hero
def moveHeroBody():
print("moveHeroBody")
self.world.delete(self.heroBody)

TA贡献1802条经验 获得超6个赞
我认为您需要Hero在 mainWindow 类中初始化该类。代码中需要做的修改是:
类.py
from tkinter import *
from time import sleep
class mainWindow():
def __init__(self):
#Setup the GUI
self.jump_gap = 25
root = Tk()
root.geometry('800x600')
# Setup the canvas within the GUI (master)
self.world = Canvas(root, height = 600, width = 800, bg = "#FFFFFF")
self.world.place(relx = 0.5, rely = 0.5, anchor = CENTER)
self.hero = Hero(self.world)
self.world.pack()
root.bind("<space>",self.jump) # -> [1] Binds the SPACE BAR Key to the function jump
root.mainloop()
def jump(self,event):
gaps = list(range(self.jump_gap))
for i in gaps:
self.world.after(1,self.hero.moveHeroJump(h=i)) # [2] -> Binds the moveHeroJump method with the window action to a queue of updates
self.world.update() #[2] updates the canvas
sleep(0.01*i) # Added some linear wait time to add some look to it
gaps.reverse()
for i in gaps:
self.world.after(1,self.hero.moveHeroJump(h=-i))
self.world.update()
sleep(0.01*i)
class Hero():
def __init__(self,world):
#Initial creation of hero at coordinates
self.world = world
self.x1 = 10
self.y1 = 410
self.x2 = 70
self.y2 = 470
self.heroBody = self.world.create_oval(self.x1,self.y1,self.x2,self.y2, fill = "#FF0000", outline = "#FF0000")
#Move the hero
def moveHeroJump(self,h):
print("moveHeroBody")
self.y1 -= h
self.y2 -= h
self.world.delete(self.heroBody)
self.heroBody = self.world.create_oval(self.x1,self.y1,self.x2,self.y2, fill = "#FF0000", outline = "#FF0000")
物理.py
from tkinter import *
from classes import *
mainWindow1 = mainWindow()
编辑
所以这让我几分钟前开始玩了,我从堆栈中研究了一些资源来完成这个问题。以下是来源(在代码中也有引用):
如何将空格键键绑定到 tkinter python 中的某个方法
移动 Tkinter 画布
上面编辑的解决方案能够执行一个简单的跳球动画。self.jump_gap是一个固定的量,它告诉球它需要跳跃多少。jump解析一定高度的方法h让moveHeroJump小球改变它的位置,改变位置后排队进入Canvas一个更新被调用来查看小球的变化。
添加回答
举报