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)
Related
For a current school project, I am making a simple animation and while trying to import threading I keep getting a not implemented error.
The animation is supposed to have two circles moving perpendicular to each other passing back and forth on the screen without colliding. I added threading, time, and simplgui to try to accomplish this but I only received the error message: "NotImplementedError: threading is not yet implemented in Skulpt".
At the very least I need to know what the error message means or an alternative way to accomplish this animation because every forum or coding site I have consulted has not given clear answers on what the issue is.
code:
import time
import threading
import simplegui
x1 = 50
y1 = 200
x2 = 200
y2 = 200
def draw_handler(canvas):
simo()
def horizontal(use2):
def reverse():
global x1
while (x1 > 50):
x1 = x1 - 5
if (x1 >= 50):
x1 = x1 - 5
canvas.draw_circle((x1, y1), 50, 1, "White", "White")
def forward():
global x1
x1 = x1 + 5
if (x1 >= 350):
reverse()
canvas.draw_circle((x1, y1), 50, 1, "White", "White")
forward()
#def verticle(use1):
def simo():
use1 = threading.thread(target=verticle)
use2 = threading.thread(target=horizontal)
frame = simplegui.create_frame('Testing', 400, 400)
frame.set_canvas_background("Black")
frame.set_draw_handler(draw_handler)
frame.start()
I'm creating 2D game and when i am trying to add more than one wall they doesn't appear on canvas.
import tkinter
root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.pack()
class wall:
point1 = []
point2 = []
def __init__(self, canvas, x1, y1, x2, y2):
self.canvas = canvas
self.point1.append(x1)
self.point1.append(y1)
self.point2.append(x2)
self.point2.append(y2)
def draw(self):
self.canvas.create_line(self.point1[0], self.point1[1], self.point2[0], self.point2[1], width = 2)
walls = []
walls.append(wall(canvas, 90, 90, 100, 200))
walls.append(wall(canvas, 90, 90, 300, 100))
def update():
for wall in walls:
wall.draw()
root.after(int(1000/60), update)
root.after(int(1000/60), update)
root.mainloop()
If I add them manually they are drawing both.
canvas.create_line(90, 90, 100, 200, width = 2)
canvas.create_line(90, 90, 300, 100, width = 2)
Consider this part of your class wall:
class wall:
point1 = []
point2 = []
...
The lists point1 and point2 are defined as class attribute instead of instance attribute. So when you append new coordinates, the previous ones are still there.
To fix this, simply make point and point2 instance attributes instead:
class wall:
def __init__(self, canvas, x1, y1, x2, y2):
self.point1 = []
self.point2 = []
...
Or use the parameters directly:
class wall:
def __init__(self, canvas, x1, y1, x2, y2):
self.canvas = canvas
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def draw(self):
self.canvas.create_line(self.x1, self.y1, self.x2, self.y2, width = 2)
Use Instance attributes instead of Class attributes.
class wall:
def __init__(self, canvas, x1, y1, x2, y2):
self.canvas = canvas
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def draw(self):
self.canvas.create_line(self.x1, self.y1, self.x2, self.y2, width=2)
I am making a game with 2 moving rectangles controlled by keypresses, w and s, Up and Down arrow. But I am only getting one of them to move (The one controlled by the arrows) despite that they have the same code and just different names. I have tried to figure it out but with no luck, so I really need some help getting the second one to move.(I have also tried outher ways I seen on this site like keysym but it didn’t work either)
Thanks!
The rectangles code:
class Block:
def __init__(self, canvas, color, x1, y1):
self.canvas = canvas
self.id = canvas.create_rectangle(20, 10, 35, 90, fill = color)
self.x1 = x1
self.y1 = y1
self.canvas.move(self.id, self.x1, self.y1)
self.speed_1 = 0
self.speed_2 = 0
self.canvas.bind_all('<KeyPress-w>', self.turn_up_1) #Not working
self.canvas.bind_all('<KeyPress-s>', self.turn_down_1) #Not working
self.canvas.bind_all('<KeyPress-Up>', self.turn_up_2) #working
self.canvas.bind_all('<KeyPress-Down>', self.turn_down_2) #working
def turn_up_1(self, evt): #Not working
self.speed_1 = -3
def turn_down_1(self, evt): #Not working
self.speed_1 = 3
def draw_1(self):
self.canvas.move(self.id, 0, self.speed_1) #Not working
def turn_up_2(self, evt): #working
self.speed_2 = -3
def turn_down_2(self, evt): #working
self.speed_2 = 3
def draw_2(self):
self.canvas.move(self.id, 0, self.speed_2) #working
block1 = Block(canvas, 'blue', 0, 0)
block2 = Block(canvas, 'red', 940, 540)
The loop:
while True:
block1.draw_1() #Not working
block2.draw_2() #Working
time.sleep(0.0333333333333333333333333333333333333333333333333333)
tk.update_idletasks()
tk.update()
I created some code to show 2 balls moving, but when I run it, it doesn't show the movement of the balls.Furthermore it stops running and ignores the infinite loop This is my code up to now:
import tkinter as tk
class ObjectHolder:
def __init__(self, pos, velocity, radius, id):
self.id = id # the id of the canvas shape
self.pos = pos # the position of the object
self.r = radius # the radius of incluence of the object
self.velocity = velocity # the velocity of the object
def moveobject(object):
x = object.pos[0] + object.velocity[0] # moves the object where
y = object.pos[1] + object.velocity[1] # 0=x and 1=y
object.pos = (x, y)
canvas.move(object, x, y)
class App():
def __init__(self, canvas):
self.canvas = canvas
self.objects = []
for i in range(0, 2):
position = ((i+1)*100, (i+1)*100)
velocity = (-(i+1)*10, -(i+1)*10)
radius = (i + 1) * 20
x1 = position[0]-radius
y1 = position[1]-radius
x2 = position[0]+radius
y2 = position[1]+radius
id = canvas.create_oval(x1, y1, x2, y2)
self.objects.append(ObjectHolder(position, velocity, radius, id))
self.symulation(self.objects)
def symulation(self, objects):
for object in objects: # this moves each object
ObjectHolder.moveobject(object)
# This part doesn't work. It is supposed to update the canvas
# and repeat forever.
self.canvas.update()
root.update()
self.canvas.after(50, self.symulation, objects)
root = tk.Tk()
canvas = tk.Canvas(root, width=800, height=600, bg="light blue")
canvas.pack()
App(canvas)
There are a number of issues with your code. One big one was the way you were updating the position of the existing canvas objects. The move() method needs to know the amount of movement (change in x and y value), not the new absolute position.
When I fixed that it turned out that the velocities were too big, so I reduced them to only be 10% of the values you had.
Another problem was with the way the ObjectHolder class was implemented. For one thing, the moveobject() method had no self argument, which it should have been using instead of having an object argument. You should probably also rename the method simply move().
The code below runs and does animate the movement.
import tkinter as tk
class ObjectHolder:
def __init__(self, pos, velocity, radius, id):
self.id = id # the id of the canvas shape
self.pos = pos # the position of the object
self.r = radius # the radius of incluence of the object
self.velocity = velocity # the velocity of the object
def moveobject(self):
x, y = self.pos
dx, dy = self.velocity
self.pos = (x + dx, y + dy)
canvas.move(self.id, dx, dy) # Amount of movement, not new position.
class App():
def __init__(self, canvas):
self.canvas = canvas
self.objects = []
for i in range(0, 2):
position = ((i+1)*100, (i+1)*100)
# velocity = (-(i+1)*10, -(i+1)*10)
velocity = (-(i+1), -(i+1)) # Much slower speed...
radius = (i + 1) * 20
x1 = position[0]-radius
y1 = position[1]-radius
x2 = position[0]+radius
y2 = position[1]+radius
id = canvas.create_oval(x1, y1, x2, y2)
self.objects.append(ObjectHolder(position, velocity, radius, id))
self.simulation(self.objects)
def simulation(self, objects):
for object in objects: # this moves each object
object.moveobject()
# This part doesn't work. It is supposed to update the canvas
# and repeat forever.
# self.canvas.update() # Not needed.
# root.update() # Not needed.
self.canvas.after(50, self.simulation, objects)
root = tk.Tk()
canvas = tk.Canvas(root, width=800, height=600, bg="light blue")
canvas.pack()
app = App(canvas)
root.mainloop() # Added.
I am trying to get the coordinates for each square on the board but the error UnboundLocalError: local variable 'x' referenced before assignment keeps showing up when I click on a square.
import tkinter
class RA:
def __init__(self):
self._columns = 8
self._rows = 8
self._root = tkinter.Tk()
self._canvas = tkinter.Canvas(master = self._root,
height = 500, width = 500,
background = 'green')
self._canvas.pack(fill = tkinter.BOTH, expand = True)
self._canvas.bind('<Configure>',self.draw_handler)
def run(self):
self._root.mainloop()
def draw(self):
self._canvas.create_rectangle(0,0,250,250,fill = 'blue',outline = 'white')
self._canvas.create_rectangle(250,250,499,499,fill = 'red',outline = 'white')
self._canvas.create_rectangle(499,499,250,250,fill = 'black',outline = 'white')
#
for c in range(self._columns):
for r in range(self._rows):
x1 = c * (column_width)#the width of the column
y1 = r * (row_height)
x2 = x1 + (column_width)
y2 = y1 + (row_height)
#3-5
def clicked(self,event: tkinter.Event):
x = event * x
y = event * y
rect = self._canvas.find_closest(x,y)[0]
coordinates = self._canvas.gettags(rect)
print(coordinates[0],coordinates[1])
def draw(self):
self._canvas.delete(tkinter.ALL)
column_width = self._canvas.winfo_width()/self._columns
row_height = self._canvas.winfo_height()/self._rows
for x in range(self._columns):
for y in range(self._rows):
x1 = x * column_width
y1 = y * row_height
x2 = x1 + column_width
y2 = y1 + row_height
r = self._canvas.create_rectangle(x1,y1,x2,y2,fill = 'blue')#,tag = (x,y))# added for the second time,
self._canvas.tag_bind(r,'<ButtonPress-1>',self.clicked)
self._canvas.create_rectangle(x1,y1,x2,y2)
self._canvas.bind('<Configure>',self.draw_handler)
def draw_handler(self,event):
self.draw()
r = RA()
r.run()
The problem is in these two lines:
def clicked(self,event: tkinter.Event):
x = event * x
You're using x on the right hand side of the expression, but x hasn't been defined anywhere. Also, you're going to have a problem because event is an object. Multiplying the object times some other number isn't likely going to do what you think it is going to do. Did you maybe intend to use event.x in the expression instead of event * x?
Getting the coordinates of the clicked item
Even though you specifically asked about the unbound local variable error, it appears you're attempting to get the coordinates of the item that was clicked on. Tkinter automatically gives the item that was clicked on the tag "current", which you can use to get the coordinates:
coordinates = self._canvas.coords("current")
From the official tk documentation:
The tag current is managed automatically by Tk; it applies to the
current item, which is the topmost item whose drawn area covers the
position of the mouse cursor (different item types interpret this in
varying ways; see the individual item type documentation for details).
If the mouse is not in the canvas widget or is not over an item, then
no item has the current tag.
This will happen with y as well. If you want x to be stored with the button, you'll need to create a Class for it, and store them as self.x and self.y. The clicked() event would be on the class itself, and then it will have access to it.
Looks like you used
x = event * x
y = event * y
when you probably wanted
x = event.x
y = event.y
The latter accesses the event object's x and y attributes instead of attempting to multiply it by an unbound variable.