Moving object on canvas python - python

I wanted to get a little square to move to the left 10 pixels every 3 seconds and my code is below. I'm not sure why it only moves once. Some help would be greatly apprecaited!
import tkinter as tk
import time
root = tk.Tk()
WIDTH = HEIGHT = 400
x1 = y1 = WIDTH / 2
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()
c1 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10)
c2 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10)
def draw_rect():
global c2
canvas.delete(c2)
c2 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="green")
def del_rect():
canvas.delete(c1)
#canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="white", opacity=0.5)
while 1:
root.update()
time.sleep(3)
del_rect()
x1 -= 10
draw_rect()
root.mainloop()

mainloop() runs loop which works until you close window - so it blocks all loop and it is executed only once and it move rectangle only once. In your version you should remove mainloop() and it will not block it - and because you use update() in loop so it will run correctly.
But you could do this in different way.
You can use root.after(3000, draw_rect) to execute draw_rect() after 3 seconds. And draw_rect() should run again root.after(3000, draw_rect) to run it again after another 3 seconds - this way it will loop and it will not blocked by mainloop() (mainloop() will run draw_rect() every 3 seconds)
Canvas has function move(object, dx, dy) so you don't have to delete rectangle and create it again.
I use 300ms to run it faster.
import tkinter as tk
# --- constants --- (PEP8: UPPER_CASE_NAMES)
WIDTH = 400
HEIGHT = 400
# --- functions ---
def move_rect():
canvas.move(c1, -10, 0) # move left
canvas.move(c2, 10, 0) # move right
# run again after 300ms
root.after(300, move_rect) # 300ms = 0.3s # I use smaller value to make it faster
# --- main ---
x1 = y1 = WIDTH / 2
root = tk.Tk()
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()
c1 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="green")
c2 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="red")
# run first time after 300ms
root.after(300, move_rect) # 300ms = 0.3s # I use smaller value to make it faster
root.mainloop()
PEP 8 -- Style Guide for Python Code
EDIT:
Version which uses variables speed1, speed2 to change direction when rectangle is near border.
import tkinter as tk
# --- constants --- (PEP8: UPPER_CASE_NAMES)
WIDTH = 400
HEIGHT = 400
# --- functions ---
def move_rect():
global speed1
global speed2
#x1, y1, x2, y2 = canvas.coords(c1)
pos = canvas.coords(c1)
if speed1 < 0 :
if pos[0] < 10:
speed1 = -speed1
else:
if pos[2] > WIDTH-10:
speed1 = -speed1
#x1, y1, x2, y2 = canvas.coords(c2)
pos = canvas.coords(c2)
if speed2 < 0:
if pos[0] < 10:
speed2 = -speed2
else:
if pos[2] > WIDTH-10:
speed2 = -speed2
canvas.move(c1, speed1, 0) # move left
canvas.move(c2, speed2, 0) # move right
# run again after 30ms
root.after(30, move_rect) # 30ms = 0.03s - I uses smaller value to make it faster
# --- main ---
x1 = y1 = WIDTH / 2
speed1 = -10
speed2 = +10
root = tk.Tk()
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()
print(dir(canvas))
c1 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="green")
c2 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="red")
# run first time after 300ms
root.after(300, move_rect) # 300ms = 0.3s - I uses smaller value to make it faster
root.mainloop()

Related

How can I move a list of tkinter lines in a set space?

import time
from tkinter import *
class Template:
def __init__(self):
self.window = Tk()
self.window.title("2D Display")
self.canvas = self.canvas_display()
self.line1 = self.line_creation(650,350,500 * .3, 1000)
self.line3 = self.line_movement_creation(0, 350,2000, 350)
self.horizon = self.canvas.create_line(0,350,2000, 350, width = 2, fill ="white")
self.speedx = 0 # x movement of line3
self.speedy = 9 # y movement of line3
self.active = True
self.pos1 = []
self.move_active() #Code that creates the problem
self.canvas.update()
def canvas_display(self): #canvas
canvas = Canvas(self.window, width=500, height=400, background='black')
canvas.pack(expand=True, fill="both")
canvas.update()
return canvas
Upwards is Initialization
def line_creation(self,x,y,x1,y1): #creation of multple lines
spacing = 0
lines = [] # could list([])
for i in range(11):
id = self.canvas.create_line( x, y, x1 + spacing, y1, width=2, fill="white")
lines.append(id)
spacing += 100
pos1 = self.canvas.coords(id)
self.pos1 = pos1
print(self.pos1)
return lines
This is the creation method for the vertices lines
def line_movement_creation(self,x,y,x1,y1):
spacing1 = 0
lines = []
for i in range(4):
id = self.canvas.create_line(x , y+spacing1, x1, y1 + spacing1, width=2, fill="white")
lines.append(id)
spacing1 += 100
#line = [] equal all horizontal and vertical, 12 - 15 equal horizontal moving lines
return lines
The is the creation for the horizontal lines
def line_update(self): #line movement method
for line in self.line3:
self.canvas.move(line, self.speedx, self.speedy)
#Create variables for all x and y values for the lines
pos = self.canvas.coords(line)
print(pos)
if pos[3] >= 800:
self.canvas.move(line, self.speedx, self.speedy - 460)
def move_active(self):
if self.active:
self.line_update()
self.window.after(40, self.move_active)
This is what moves the lines creating an illusion of movement. I want to take the list of horizontal lines and set them between the outer most vertical lines. So it would stay between the vertical lines. Creating a road like image. I think I need to make a separate list for both but I am not sure. So to clarify I can someone help show me how to make the horizontal lines not attach to the ends of the screen but to inside the horizontal lines Code Demonstration
def run(self):
self.window.mainloop()
if __name__ == '__main__':
Temp = Template()
Temp.run()
So, first I would suggest that you use some game engine like pygame because it is faster and provides a bit more options and other stuff but here it is with tkinter (basically it is some simple trigonometry):
import tkinter as tk
import math
class Canvas(tk.Canvas):
def __init__(self, parent, width=700, height=500, **kwargs):
super().__init__(parent, width=width, height=height, **kwargs)
self.width = width
self.height = height
self.angle = 70
self.speedy = 10
self.change_speed_ms = 50
self.draw_angle(self.angle, 5)
self.lines, self.interval = self.init_lines(amount=5)
self.draw_lines()
#property
def radians(self):
return math.radians(self.angle)
def draw_angle(self, view_angle, lines):
orient = 0
adjacent = self.height // 2
step = view_angle // lines
half = view_angle // 2
for angle in range(orient - half, orient + half + step, step):
rad = math.radians(angle)
delta = math.tan(rad) * adjacent
x1, y1 = self.width // 2, self.height // 2
x2, y2 = x1 + delta, y1 + adjacent
self.create_line(x1, y1, x2, y2)
def init_lines(self, amount=5):
interval = round((self.height // 2) / amount)
coordinate_list = list()
offset = self.height // 2
for y in range(0, self.height // 2 + interval, interval):
delta = math.tan(self.radians / 2) * y
x1 = self.width // 2 - delta
x2 = self.width // 2 + delta
y1 = y2 = y + offset
line = self.create_line(x1, y1, x2, y2)
coordinate_list.append((line, (x1, y1, x2, y2)))
return coordinate_list, interval
def draw_lines(self):
tmp_lst = list()
for id_, (x1, y1, x2, y2) in self.lines:
y1 += self.speedy
if y1 > self.height + self.interval - self.speedy:
y1 = self.height // 2
y = y2 = y1
adjacent = y - self.height // 2
delta = math.tan(self.radians / 2) * adjacent
x1 = self.width // 2 - delta
x2 = self.width // 2 + delta
self.coords(id_, x1, y1, x2, y2)
tmp_lst.append((id_, (x1, y1, x2, y2)))
self.lines = tmp_lst
self.after(self.change_speed_ms, self.draw_lines)
root = tk.Tk()
Canvas(root, highlightthickness=0).pack()
root.mainloop()
So the main method here is Canvas().draw_lines(). First of you get a list of line IDs and their coordinates at set intervals based on the amount of total lines, then you iterate over them, change their y value and accordingly calculate the opposite side of a right-angle triangle using tan and the adjacent side which is known from the current y coordinate and the starting point (the middle).

Why is nothing moving in this python script?

So I copied this code from a python book, and the code is meant to be like an egg catcher game, however if you run the code, you can see, tkinter creates everything and the game sets up, however, the game itself does not start. Does anyone know how to make it start? I tried pressing buttons and making the whole thing a function, however, they both do not work. Here is my code below...
from itertools import cycle
from random import randrange
from tkinter import Canvas, Tk, messagebox, font
canvas_width = 800
canvas_height = 400
root = Tk()
c = Canvas(root, width=canvas_width, height=canvas_height, background='deep sky blue')
c.create_rectangle(-5, canvas_height - 100, canvas_width + 5, canvas_height + 5, \
fill='sea green', width=0)
c.create_oval(-80, -80, 120, 120, fill='orange', width=0)
c.pack()
color_cycle = cycle(['light blue', 'light green', 'light pink', 'light yellow', 'light cyan'])
egg_width = 45
egg_height = 55
egg_score = 10
egg_speed = 500
egg_interval = 4000
difficulty_factor = 0.95
catcher_color = 'blue'
catcher_width = 100
catcher_height = 100
catcher_start_x = canvas_width / 2 - catcher_width / 2
catcher_start_y = canvas_height - catcher_height - 20
catcher_start_x2 = catcher_start_x + catcher_width
catcher_start_y2 = catcher_start_y + catcher_height
catcher = c.create_arc(catcher_start_x, catcher_start_y, \
catcher_start_x2, catcher_start_y2, start=200, extent=140, \
style='arc', outline=catcher_color, width=3)
game_font = font.nametofont('TkFixedFont')
game_font.config(size=18)
score = 0
score_text = c.create_text(10, 10, anchor='nw', font=game_font, fill='darkblue', \
text='Score: ' + str(score))
lives_remaining = 3
lives_text = c.create_text(canvas_width - 10, 10, anchor='ne', font=game_font, fill='darkblue', \
text='Lives: ' + str(lives_remaining))
eggs = []
def create_egg():
x = randrange(10, 740)
y = 40
new_egg = c.create_oval(x, y, x + egg_width, y + egg_height, fill=next(color_cycle), width=0)
eggs.append(new_egg)
root.after(egg_interval, create_egg)
def move_eggs():
for egg in eggs:
(egg_x, egg_y, egg_x2, egg_y2) = c.coords(egg)
c.move(egg, 0, 10)
if egg_y2 > canvas_height:
egg_dropped(egg)
root.after(egg_speed, move_eggs)
def egg_dropped(egg):
eggs.remove(egg)
c.delete(egg)
lose_a_life()
if lives_remaining == 0:
messagebox.showinfo('Game Over!', 'Final Score: ' + str(score))
root.destroy()
def lose_a_life():
global lives_remaining
lives_remaining -= 1
c.itemconfigure(lives_text, text='Lives: ' + str(lives_remaining))
def check_catch():
(catcher_x, catcher_y, catcher_x2, catcher_y2) = c.coords(catcher)
for egg in eggs:
(egg_x, egg_y, egg_x2, egg_y2) = c.coords(egg)
if catcher_x < egg_x and egg_x2 < catcher_x2 and catcher_y2 - egg_y2 < 40:
eggs.remove(egg)
c.delete(egg)
increase_score(egg_score)
root.after(100, check_catch)
def increase_score(points):
global score, egg_speed, egg_interval
score += points
egg_speed = int(egg_speed * difficulty_factor)
egg_interval = int(egg_interval * difficulty_factor)
c.itemconfigure(score_text, text='Score: ' + str(score))
def move_left(event):
(x1, y1, x2, y2) = c.coords(catcher)
if x1 > 0:
c.move(catcher, -20, 0)
def move_right(event):
(x1, y1, x2, y2) = c.coords(catcher)
if x2 < canvas_width:
c.move(catcher, 20, 0)
c.bind('<Left>', move_left)
c.bind('<Right>', move_right)
c.focus_set()
root.after(1000, create_egg)
root.after(1000, move_eggs)
root.after(1000, check_catch)
root.mainloop()
I see lots of functions but no calls to them, especially the function that runs the Tkinter main loop.
Given the similarity you would expect between the move_left() and move_right() functions, it's a near certainty that the final lines of the latter should not be indented to where they are.
With your current code, the lines doing the binding and timer call-back setups are only executed when move_right() is called. Which it isn't, because the key binding that would call it is only set up when it's called (which it isn't because ...
WARNING W-42: thought process terminated due to likely stack overflow in wet-ware :-)
In other words, your code should be something like:
def move_left(event):
(x1, y1, x2, y2) = c.coords(catcher)
if x1 > 0:
c.move(catcher, -20, 0)
def move_right(event):
(x1, y1, x2, y2) = c.coords(catcher)
if x2 < canvas_width:
c.move(catcher, 20, 0)
# Run this at top level, NOT as part of move_right().
c.bind('<Left>', move_left)
c.bind('<Right>', move_right)
c.focus_set()
root.after(1000, create_egg)
root.after(1000, move_eggs)
root.after(1000, check_catch)
root.mainloop()
As an aside, it may just be the way you pasted the code in, but you should try to follow the PEP8 style guide when writing code, specifically the four-space-indent guideline. They generally make your code much easier to read and/or analyse.
And, just so you're aware, those move_xxx() functions will actually allow your catcher to go off the edges of the screen (up to twenty pixels, I think). If that's not what you want, you may want to make a small change:
move_sz = 20
def move_left(event):
(x1, y1, x2, y2) = c.coords(catcher)
c.move(catcher, -min(move_sz, x1), 0)
def move_right(event):
(x1, y1, x2, y2) = c.coords(catcher)
c.move(catcher, min(move_sz, canvas_width - x2 - 1), 0)
I haven't tested that (particularly the possibility of being out by one pixel - I'll leave that up to you) but the idea is just to limit how much you move if that would send your catcher outside the canvas bounds.
You'll see I've also replaced the magic constant 20 with a more appropriate variable - that's so you only need to change it in one place should you want to adjust the movement speed.

python tkinter bouncing ball game

I'm making a basic game. I want the ball to bounce back up ONLY when it hits the platform. So far, I've written code that will make the ball bounce off the top and bottom screen, but I'm having trouble with getting the ball to bounce off the platform.
from tkinter import *
import time
import tkinter
tk = Tk()
canvas = Canvas(tk, bg="white",width=(900),height=(500))
canvas.pack()
platform = canvas.create_rectangle(400,400,500,410)
def ball():
xspeed = 2
yspeed = 2
ball = canvas.create_oval(430,10,470,50)
while True:
canvas.move(ball, xspeed, yspeed)
pos = canvas.coords(ball)
if pos[2] >=900 or pos[0] <0:
xspeed = -xspeed
tk.update()
time.sleep(0.01)
def board():
board_right()
board_left()
def board_right(event):
xspeed = 5
yspeed = 0
canvas.move(platform,xspeed,yspeed)
tk.update
time.sleep(0.01)
def board_left(event):
xspeed = 5
yspeed = 0
canvas.move(platform,-xspeed,yspeed)
tk.update()
time.sleep(0.01)
canvas.bind_all("<Right>",board_right)
canvas.bind_all("<Left>",board_left)
ball()
tk.mainloop()
Do not use time.sleep() as it will block the tkinter mainloop, use after() instead.
To check whether the ball hits the platform, you need to get the center x of the ball and the lower y of the ball. If center x is within the left and right of platform and the ball lower y is the platform upper y, then reverse the ball y speed. Otherwise game over!
Below is sample code based on yours:
import tkinter as tk
root = tk.Tk()
width = 900
height = 500
canvas = tk.Canvas(root, bg='white', width=width, height=height)
canvas.pack()
ball = canvas.create_oval(430, 10, 470, 50, fill='green')
platform_y = height - 20
platform = canvas.create_rectangle(width//2-50, platform_y, width//2+50, platform_y+10, fill='black')
# ball moving speed
xspeed = yspeed = 2
def move_ball():
global xspeed, yspeed
x1, y1, x2, y2 = canvas.coords(ball)
if x1 <= 0 or x2 >= width:
# hit wall, reverse x speed
xspeed = -xspeed
if y1 <= 0:
# hit top wall
yspeed = 2
elif y2 >= platform_y:
# calculate center x of the ball
cx = (x1 + x2) // 2
# check whether platform is hit
px1, _, px2, _ = canvas.coords(platform)
if px1 <= cx <= px2:
yspeed = -2
else:
canvas.create_text(width//2, height//2, text='Game Over', font=('Arial Bold', 32), fill='red')
return
canvas.move(ball, xspeed, yspeed)
canvas.after(20, move_ball)
def board_right(event):
x1, y1, x2, y2 = canvas.coords(platform)
# make sure the platform is not moved beyond right wall
if x2 < width:
dx = min(width-x2, 10)
canvas.move(platform, dx, 0)
def board_left(event):
x1, y1, x2, y2 = canvas.coords(platform)
# make sure the platform is not moved beyond left wall
if x1 > 0:
dx = min(x1, 10)
canvas.move(platform, -dx, 0)
canvas.bind_all('<Right>', board_right)
canvas.bind_all('<Left>', board_left)
move_ball()
root.mainloop()

How do I get a ball to glide in python tkinter?

I have this program that I tried to make in python tkinter. A ball would appear on screen and every time I click I want the ball to glide to the point at which I clicked. The x and y locations of the ball changed but the ball only redraws after the ball is finished "moving." Can someone tell me what I am doing wrong.
from tkinter import *
import time
width = 1280
height = 700
ballRadius = 10
iterations = 100
mouseLocation = [width/2, height/2]
ballLocation = [width/2, height/2]
root = Tk()
def drawBall(x, y):
canvas.delete(ALL)
canvas.create_oval(x - ballRadius, y - ballRadius, x + ballRadius, y + ballRadius, fill="blue")
print(x, y)
def getBallLocation(event):
mouseLocation[0] = event.x
mouseLocation[1] = event.y
dx = (ballLocation[0] - mouseLocation[0]) / iterations
dy = (ballLocation[1] - mouseLocation[1]) / iterations
for i in range(iterations):
ballLocation[0] -= dx
ballLocation[1] -= dy
drawBall(round(ballLocation[0]), round(ballLocation[1]))
time.sleep(0.02)
ballLocation[0] = event.x
ballLocation[1] = event.y
canvas = Canvas(root, width=width, height=height, bg="black")
canvas.pack()
canvas.create_oval(width/2-ballRadius, height/2-ballRadius, width/2+ballRadius, height/2+ballRadius, fill="blue")
canvas.bind("<Button-1>", getBallLocation)
root.mainloop()
In your code time.sleep pauses the entire GUI, that's why you don't see the intermediate locations of the ball. Instead you can construct a function with widget.after method. Try the following:
print(x, y)
dx = 0
dy = 0
def getBallLocation(event):
canvas.unbind("<Button-1>")
global dx, dy
mouseLocation[0] = event.x
mouseLocation[1] = event.y
dx = (ballLocation[0] - mouseLocation[0]) / iterations
dy = (ballLocation[1] - mouseLocation[1]) / iterations
draw()
i = 0
def draw():
global i
ballLocation[0] -= dx
ballLocation[1] -= dy
drawBall(round(ballLocation[0]), round(ballLocation[1]))
if i < iterations-1:
canvas.after(20, draw)
i += 1
else:
canvas.bind("<Button-1>", getBallLocation)
i = 0
canvas = Canvas(root, width=width, height=height, bg="black")

How to start new level when widget on tkinter overlaps another widget?

so there are a lot of problems going on with this. I attempted to make a snake game in python but It was just a mess so now I'm trying to make it where the only direction they can go after the initial right movement is down and they have to get to the coordinates of the food otherwise it starts over. if they 'eat' the food/square then it will make another level with ought starting new game so I can keep score, however the grow definition doesn't seem to be working at all no matter what I put under the if's. Im using python tkinter.
import Tkinter
import random
import math
from Tkinter import *
import time
# Create root window
####
root = Tkinter.Tk()
#####
# Create Model
######
speed_intvar = Tkinter.IntVar()
speed_intvar.set(1) # Initialize y coordinate
# radius and x-coordinate of circle
new_dir = 0
leng = 40
var = 1
x1 = 10
y1 = 10
x2 = 50
y2 = 10
x3 = x2
y3 = 10
direction = 3
foodx1 = 1
foodx2 = 8
foody1 = 1
foody2 = 8
food_present = 0
length = 8
food = 0# radians of angle in standard position, ccw from positive x axis
######
# Create Controller
#######
# Instantiate and place slider
# Create and place directions for the user
#canvas = Tkinter.Canvas(root, width=900, height=900, background='#FFFFFF')
#canvas.grid(row=0, rowspan=2, column=2)
#text = Tkinter.Button(root, text='Use WASD to move', command = new_game)
#text.grid(row=0, column =2)
#text = Tkinter.Label(root, text='Use WASD to move')
#text.grid(row=0, column =2)
######
# Create View
#######
# Create and place a canvas
def new_game():
c.delete("all")
canvas = Tkinter.Canvas(root, width=900, height=900, background='#FFFFFF')
canvas.grid(row=0, rowspan=2, column=1)
# Create a circle on the canvas to match the initial model
circle_item = canvas.create_line(x1, y1, x2, y2, x2, y3, fill='black', width = "8")
#circle_item2 = canvas.create_rectangle(8, 1, 9, 8,
# outline='#000000', fill='black')
#def move(event):
# if event.char=='w'
def food():
global foodx1, foodx2, foody1, foody2, food_present, food, var
food_present = 0
if food_present==0:
foodx1 = random.randint(1, 900)
foody1 = random.randint(1,900)
foodx2 = foodx1 + 8
foody2 = foody1 + 8
food = canvas.create_rectangle(foodx1, foody1, foodx2, foody2, fill = 'black')
food_present += 1
food()
#def make_longer():
# global food_present, food_list, x1, y1, x2, y2, circle_item
# #x1 = canvas.coords(circle_item)
# #y1 = canvas.coords(circle_item)
# #x2 = canvas.coords(circle_item)
# #y2 = canvas.coords(circle_item)
# xx1, yy1, xx2, yy2 = canvas.coords(circle_item)
# xx1 -= 10
# xx2 -= 50
# for i in range(len(food_list)):
# circle_item2=canvas.create_rectangle(xx1, yy1, xx2, yy2, fill ="black")
#make_longer()
def animate():
global x1, y1, x2, y2, x3, y3, var
x1, y1, x2, y2, x3, y3 = canvas.coords(circle_item)
#for i in range(food_present):
if var == 1:
x1 += 1
x2 += 1
#x3+= 1
if var == 4:
y1+=1
y2+=1
y3+=1
if var == 5:
x1-=1
x2-=1
x3-=1
if var == 6:
y1 -= 1
y2 -= 1
y3 -= 1
canvas.coords(circle_item, x1, y1, x2, y2, x2, y3)
#canvas.itemconfig(circle_item, x1, y1, x2, y2, x3, y3, fill="blue")
canvas.update()
#
#while
# Get the slider data and create x- and y-components of velocity
#velocity_x = speed_intvar.get() * math.cos(direction) # adj = hyp*cos()
#velocity_y = speed_intvar.get() * math.sin(direction) # opp = hyp*sin()
## Change the canvas item's coordinates
#canvas.move(circle_item, velocity_x, velocity_y)
#canvas.move(circle_item2, velocity_x, velocity_y)
# Get the new coordinates and act accordingly if ball is at an edge
#global location
## If crossing left or right of canvas
#if x2>canvas.winfo_width():
#
#if x1<0:
# canvas.move(circle_item, x+400, y)
#global direction
canvas.after(1, animate)
# Call function directly to start the recursion
animate()
#
def move(event):
global direction, var, x1, x2, x3, y1, y2, y3, new_dir
direction = 3
if event.char=='s' and direction == 3:
if direction == 1:
return
else:
new_dir = 1
var = 3
for i in range(10):
x1, y1, x2, y2, x3, y3 = canvas.coords(circle_item)
#for i in range(food_present):
if var == 3:
x1 += 1
x2 += 0
x3 +=0
y1 +=0
y2= y1
#x2 += 1
#x3 += 1
y3 += 1
canvas.coords(circle_item, x1, y1, x2, y2, x3, y3)
canvas.update()
if x1 == x3:
var = 4
direction = 1
canvas.update()
# if event.char=='s' and direction == 2:
# if direction == 1:
# return
# else:
# new_dir = 1
# var = 3
# for i in range(10):
# x1, y1, x2, y2, x3, y3 = canvas.coords(circle_item)
##for i in range(food_present):
# if var == 3:
# x1 -= 0
# x2 -= 1
# x3 -=1
# y1 -=0
# y2 -=1
# #x2 += 1
# #x3 += 1
#
# y3 -= 1
# canvas.coords(circle_item, x1, y1, x2, y2, x3, y3)
# canvas.update()
# if x1 == x3:
# var = 4
# direction = 1
# canvas.update()
root.bind("<Key>", move)
def x():
i = Tkinter.Canvas(root, width=900, height=900, background='#FFFFFF')
x = Tkinter.Button(root, text='Use S to move down. Try and eat the food.', command = new_game)
x.grid(row=0, column =1)
def grow():
global x1, y1, x2, y2, x3, y3, var, food_present, foodx1, foody1, foodx2, foody2
x1, y1, x2, y2, x3, y3 = canvas.coords(circle_item)
if x2>canvas.winfo_width() or x1<0:
x()
if y2>canvas.winfo_height() or y3>canvas.winfo_height():
food_present = 0
x()
canvas.update()
grow()
c = Tkinter.Canvas(root, width=900, height=900, background='#FFFFFF')
c.grid(row=0, rowspan=2, column=1)
text = Tkinter.Button(root, text='Use S to move down. Try and eat the food.', command = new_game)
text.grid(row=0, column =1)
root.mainloop()
If you want to check if two objects are overlapping on a Tkinter canvas, you may get their positions by the method of object Canvas .coords(objectname). You use the .coords method to check on a drawn object.
Example:
circle = canvas.create_oval(0, 0, 50, 50)
canvas.move(circle, 5, 0) # moves the circle by 5 pixels to the right
coords = canvas.coords(circle) # Returns an array (5, 0, 55, 0).
What you don't do is specify a coordinate to return what object is on it(what I think you are doing).

Categories

Resources