python方法调用名字不一样怎么办_NameError:从类中调用方法时,Python未定义名称“self”...

我做了这样的东西:

它使用self.root,所以我可以在moveBall中使用它,它与self.root.after(15, moveBall)一起使用,15毫秒后再次运行{},我不需要while True。我不需要canvas.after(15)和{}。在

我从class Application(Frame):中删除了Frame,因为您将所有小部件直接添加到root中,而这个{}从未使用过。在小部件中,您必须使用self而不是root来将小部件添加到此Frame,而{}则必须使用master=root将它们添加到主窗口。在from tkinter import *

class Application():

def __init__(self):

# Constructing the Screen

self.root = Tk()

self.canvas = Canvas(self.root, width=800, height=400)

# Label

self.v = StringVar()

self.l = 5

self.label = Label(self.root, textvariable=self.v, font=('Courier',

20), bg='white', width=50)

self.v.set('Lives: ' + str(self.l))

self.label.grid()

self.canvas.grid()

# Ball

self.canvas.create_oval(

2,

2,

22,

22,

fill='red',

tags='ball',

)

# Paddle

self.canvas.create_rectangle(

360,

380,

440,

400,

fill='black',

tag='paddle',

)

# Keybindings

self.canvas.focus_set()

self.canvas.bind('', self.paddleLeft)

self.canvas.bind('a', self.paddleLeft)

self.canvas.bind('', self.paddleLeft)

self.canvas.bind('', self.paddleRight)

self.canvas.bind('d', self.paddleRight)

self.canvas.bind('', self.paddleRight)

# Logic

self.horizontal_direction = 'east'

self.vertical_direcction = 'south'

# run after 250ms so mainloop has time to start

self.root.after(250, self.moveBall)

self.root.mainloop()

def collide(self):

(x1, y1, x2, y2) = self.canvas.coords('ball')

(px1, py1, px2, py2) = self.canvas.coords('paddle')

if x2 >= 800:

self.horizontal_direction = 'west'

if x1 <= 0:

self.horizontal_direction = 'east'

if y1 <= 0:

self.vertical_direcction = 'south'

if y2 >= 400:

self.l -= 1

self.v.set('Lives: ' + str(self.l))

self.vertical_direcction = 'north'

if y2 >= py1:

if x1 in range(int(px1), int(px2)) or x2 in range(int(px1),

int(px2)):

self.vertical_direcction = 'north'

def moveBall(self):

if self.horizontal_direction == 'east':

self.canvas.move('ball', 2, 0)

else:

self.canvas.move('ball', -2, 0)

if self.vertical_direcction == 'south':

self.canvas.move('ball', 0, 2)

else:

self.canvas.move('ball', 0, -2)

self.collide()

# run again after 15ms - so I don't need `while True`

self.root.after(15, self.moveBall)

def paddleLeft(self, event):

(px1, py1, px2, py2) = self.canvas.coords('paddle')

if px1 >= 0:

self.canvas.move('paddle', -5, 0)

def paddleRight(self, event):

(px1, py1, px2, py2) = self.canvas.coords('paddle')

if px2 <= 800:

self.canvas.move('paddle', 5, 0)

# - start -

Application()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值