简体   繁体   中英

AttributeError: 'Event' object has no attribute 'wider'

I have this program in which I draw a rectangle on a canvas and when I press either the < arrow key or the > key the rectangle should get wider or narrower. But when I run this program and press either of those keys the python shell prints out AttributeError: 'Event' object has no attribute 'wider' (or 'narrower')... A. How can I fix this? and B. Why does it do that?

from tkinter import *
root = Tk()
canvas = Canvas(root, width=400, height=300, bg="#000000")
canvas.pack()
x1 = 150
y1 = 100
x2 = 250
y2 = 200
class ResizeRect:
     def __init__(self, x1, y1, x2, y2):
         self.x1 = x1
         self.y1 = y1
         self.x2 = x2
         self.y2 = y2
         self.rect = canvas.create_rectangle(0,0,1,1)
     def draw(self):
         canvas.delete(self.rect)
         self.rect = canvas.create_rectangle(x1, y1, x2, y2,outline="#00B000", width=2)
     def narrower(self):
         self.x1 = self.x1 + 5
         self.x2 = self.x2 - 5
     def wider(self):
         self.x1 = self.x1 - 5
         self.x2 = self.x2 + 5
r = ResizeRect(150, 100, 250, 200)
r.draw()
def left(r):
    r.narrower()
def right(r):
    r.wider()
canvas.bind_all('<KeyPress-Left>', left)
canvas.bind_all('<KeyPress-Right>', right)

I also don't know if/when I fix this, there will still be a ton of errors. So it would be great if you help me with the specific problem. But it would be even cooler if you could tell me if/how to fix the other errors that come after this one.

Thanks

You need to provide an argument for the event that tkinter sends when using bind :

def left(event):
    r.narrower()

Those methods will also need to call canvas.coords ; simply updating the numbers won't cause the display to change.

Your left() and right() routines are receiving an event , which you are not currently accepting. You can change your routines to be like this:

def left(e):
    r.narrower()
def right(e):
    r.wider()

This gets rid of your error messages. The routines for narrowing and widening will now be called, but they won't work. To resize the rectangle, you'll need to work with the coords() method. By changing the coordinates of the rectangle, you can effectively move or resize it.

current_coords = canvas.coords(rectangleTagId)
# update the coords to new_coords
canvas.coords(rectangleTagId, *new_coords)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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