Why doesn't this image move when the key is pressed? - python

Python and Tkinter nebwie. I tried making an image in tkinter and have it move using the arrows. The image shows just it should, but when I try to move it using the arrows, it doesn't work at all. Any idea why? I use python 2.7.18 and I'm on the latest version of Ubuntu
from Tkinter import *
############
#things
w = 500
h = 500
width=w
height=h
#############
######################################################################
#window
window = Tk()
window.title("Moving image")
canvas = Canvas(window, width = 500, height = 500)
canvas.pack()
my_image = PhotoImage(file="/home/user/Documents/ddd.png")
canvas.create_image(260, 125, anchor = NW, image=my_image)
#######################################################################
################################
#var
def up(event):
x = 0
y = -10
canvas.move(my_image, x, y)
def down(event):
x = 0
y = 10
canvas.move(my_image, x, y)
def left(event):
x = -10
y = 0
canvas.move(my_image, x, y)
def right(event):
x = 10
y = 0
canvas.move(my_image, x, y)
###############################
###############################
#binds
window.bind("<Up>", up)
window.bind("<Down>", down)
window.bind("<Left>", left)
window.bind("<Right>", right)
window.mainloop()
##############################

You are trying to move the wrong object. Use the object, which is returned by canvas.create_image:
image_id = canvas.create_image(260, 125, anchor = NW, image=my_image)
...
canvas.move(image_id, x, y)
Alternatively, you can attach a tag to the image:
canvas.create_image(260, 125, anchor=NW, image=my_image, tag="move")
...
canvas.move("move", x, y)
This will move all objects, which have this specific tag attached.

Related

Tkinter smooth transition between frames

# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk
# Create an instance of tkinter frame
win = Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Define a Canvas widget
canvas = Canvas(win, width=600, height=400, bg="white")
canvas.pack(pady=20)
# Add Images to Canvas widget
x = 250
y = 120
image = ImageTk.PhotoImage(Image.open('map.png'))
img = canvas.create_image(x, y, anchor=NW, image=image)
def left(e):
global x, y
x -= 0.9
canvas.coords(img, x, y)
def right(e):
global x, y
x += 0.9
canvas.coords(img, x, y)
def up(e):
global x, y
y -= 0.9
canvas.coords(img, x, y)
def down(e):
global x, y
y += 0.9
canvas.coords(img, x, y)
# Bind the move function
win.bind("<Left>", left)
win.bind("<Right>", right)
win.bind("<Up>", up)
win.bind("<Down>", down)
win.mainloop()
map.png is https://www.dropbox.com/s/wfq4skai66nexxr/map.png?dl=0. If you press left or right arrow keys, you will see the black words look slightly lagging. Is there a way to fix that without changing the 0.9?

Python tkinter get color from canvas

I have created a simple Tkinter application with a canvas widget like this:
from tkinter import *
root = Tk()
root.geometry("500x500-500+500")
canvas = Canvas(root, width = 400, height = 400, bg = "white")
canvas.pack()
canvas.create_line(0, 0, 200, 100, width = 20, fill = "black")
root.mainloop()
My question is, how can I get the color of the canvas in a specific position? Say for instance I clicked somewhere on the line, how can I get back the color "black" from that?
In other words, if I wanted a function like this,
def getColor(cnvs, event = None):
x = event.x
y = event.y
# somehow gets the color of cnvs at position (x, y) and stores it as color
return color
how would I go about doing that?
You can take a screen shot of the canvas using Pillow.ImageGrab module and get the required pixel color from the snapshot image:
from PIL import ImageGrab
def get_color(cnvs, event):
x, y = cnvs.winfo_rootx()+event.x, cnvs.winfo_rooty()+event.y
# x, y = cnvs.winfo_pointerx(), cnvs.winfo_pointery()
image = ImageGrab.grab((x, y, x+1, y+1)) # 1 pixel image
return image.getpixel((0, 0))
Note that the color returned is in (R, G, B) format.

tkinter: Moving objects to random places using a for loop

I use python tkinter and I am trying to move my ark/sun (ONLY 1 onject) to random places across (0,500) to (800,500) using a for loop so every time I run it will be in a new place but i keep failing to do so. If someone could help me it would mean a lot.
from tkinter import *
from random import *
myInterface = Tk()
screen = Canvas( myInterface, width=800, height=800, background="white" )
screen.pack()
#sky
##Sky
y = 0
y2 = 22
skyOptions = ["#4C1D6D","#53236E","#5A2970","#623072","#693674","#703D75",\
"#784377","#7F4979","#86507B","#8E567C","#955D7E","#9C6380",\
"#A46A82","#AB7083","#B27685","#BA7D87","#C18389","#C88A8A",\
"#D0908C","#D7968E","#DE9D90","#E6A391", "#EDAA93","#F4B095"]
for sky in range (1,24):
skyColour = (skyOptions[sky%24])
screen.create_rectangle (0,y,1000,y2, fill = skyColour, outline = skyColour)
y = y + 22
y2 = y2 + 22
#sun (Make it randomly move plz)
screen.create_arc(150, 250, 500, 800 ,start=0, extent=180, fill= "#fd8953", outline = "#fd8953")
screen.update
spacing = 50
for x in range(0, 1000, spacing):
screen.create_line(x, 25, x, 1000, fill="red")
screen.create_text(x, 5, text=str(x), font="Times 9", anchor = N)
for y in range(0, 1000, spacing):
screen.create_line(25, y, 1000, y, fill="blue")
screen.create_text(5, y, text=str(y), font="Times 9", anchor = W)
screen.update()
A simple example of moving a widget on a canvas using the coords() function:
from tkinter import *
from random import *
myInterface = Tk()
screen = Canvas( myInterface, width=800, height=800, background="white" )
screen.pack()
#sun (Make it randomly move plz)
arc = screen.create_arc(150, 250, 500, 800 , start=0, extent=180,
fill= "#fd8953", outline = "#fd8953")
def random_move(event):
# Generate random numbers for x and y between 0 and 99
x = randrange(0, 100)
y = randrange(0, 100)
# Move arc to original + random x, y position
screen.coords(arc, [150+x, 250+y, 500+x, 800+y])
# Create binding so random_move() is easy to invoke.
myInterface.bind('<space>', random_move)
# start mainloop() which runs the application
myInterface.mainloop()
You need to start the application mainloop or the program will just stop after creating the window and widgets. The mainloop listens for events (mouse, keyboard ect).
Also: that was a lot of code, most of which was not relevant to your problem. Try to minimize the code in your questions.
I'm binding <space> to the random_move() function so just hit space for each move.
And; check out The Tkinter Canvas Widget.

Tkinter when a button is clicked?

So im making a game in Tkinter but what I want to do is when I click a button on my keyboard for example "w" it runs a function that increments x by 5 for example.
Heres my code.
__author__ = 'Zac'
from Tkinter import *
from random import randint
class Application:
def circle(self, r, x, y):
return (x-r, y-r, x+r, y+r)
def square(self, s, x, y):
return (x, y, s, s)
def __init__(self, canvas, r, x, y):
self.canvas = canvas
self.r = r
self.x = x
self.y = y
self.ball = canvas.create_oval(self.circle(r, x, y))
root = Tk()
canvas = Canvas(root, width = 1000, height = 1000)
canvas.pack()
ball1 = Application(canvas, 20, 50, 50)
root.mainloop()
Use widget.bind method to bind keypress with event handler.
For example:
....
ball1 = Application(canvas, 20, 50, 50)
def increase_circle(event):
canvas.delete(ball1.ball)
ball1.r += 5
ball1.ball = canvas.create_oval(ball1.circle(ball1.r, ball1.x, ball1.y))
root.bind('<w>', increase_circle) # <--- Bind w-key-press with increase_circle
root.mainloop()
See Events and Bindings.

How to move a Canvas image using Tkinter?

Guys I am working on a code which needs to move an image in python using Tkinter(canvas)
This is creating problems for me. The image is being displayed but it is not moving.
from Tkinter import *
root = Tk()
root.title("Click me!")
def next_image(event):
global toggle_flag
global x, y, photo1
# display photo2, move to right, y stays same
canvas1.create_image(x+10, y, image=photo1)
canvas1.create_image(x+20, y, image=photo1)
canvas1.create_image(x+30, y, image=photo1)
canvas1.create_image(x+40, y, image=photo1)
canvas1.create_image(x+50, y, image=photo1)
canvas1.create_image(x+60, y, image=photo1)
canvas1.create_image(x+70, y, image=photo1)
canvas1.create_image(x+100, y, image=photo1)
image1 = "C:\Python26\Lib\site-packages\pygame\examples\data\ADN_animation.gif" #use some random gif
photo1 = PhotoImage(file=image1)
# make canvas the size of image1/photo1
width1 = photo1.width()
height1 = photo1.height()
canvas1 = Canvas(width=width1, height=height1)
canvas1.pack()
# display photo1, x, y is center (anchor=CENTER is default)
x = (width1)/2.0
y = (height1)/2.0
canvas1.create_image(x, y, image=photo1)
canvas1.bind('<Button-1>', next_image) # bind left mouse click
root.mainloop()
Canvas provides move method. Arguments are item you want to move, relative x offset from the previous position, y offset.
You need to save the return value of the create_image to pass it to the move method.
Also make sure the canvas is expandable (pack(expand=1, fill=BOTH) in the following code)
from Tkinter import *
root = Tk()
def next_image(event):
canvas1.move(item, 10, 0) # <--- Use Canvas.move method.
image1 = r"C:\Python26\Lib\site-packages\pygame\examples\data\ADN_animation.gif"
photo1 = PhotoImage(file=image1)
width1 = photo1.width()
height1 = photo1.height()
canvas1 = Canvas(width=width1, height=height1)
canvas1.pack(expand=1, fill=BOTH) # <--- Make your canvas expandable.
x = (width1)/2.0
y = (height1)/2.0
item = canvas1.create_image(x, y, image=photo1) # <--- Save the return value of the create_* method.
canvas1.bind('<Button-1>', next_image)
root.mainloop()
UPDATE according to the comment
Using after, you can schedule the function to be called after given time.
def next_image(event=None):
canvas1.move(item, 10, 0)
canvas1.after(100, next_image) # Call this function after 100 ms.

Categories

Resources