N
N
NightCAT_Busya2021-05-20 18:53:52
Python
NightCAT_Busya, 2021-05-20 18:53:52

Python Tkinter Canvas Objects?

The code:

from tkinter import*
from PIL import ImageTk, Image
from tkinter import Canvas
import random
import time
root=Tk()
root.geometry("700x700")
canvas=Canvas()
canvas.pack(fill=BOTH, expand=1)
def rect():
    x=random.randint(10, 690)
    y=random.randint(10, 100)
    x2=random.randint(60, 290)
    y2=random.randint(60, 200)
    canvas.create_rectangle(
        x, y, x2, y2,
        outline="#f11", fill="red", width=5
    )
    for meow in range(100000):
        canvas.move(1, 0, 1)
        time.sleep(0.01)
        canvas.update()
 
def istr():   
    i=PhotoImage(file='C:\Python\\istrebitel.gif')
    i=i.subsample(3, 3)
    canvas.create_image(200, 200, anchor=NW, image=i)
    
    def movetriangle(event):
        if event.keysym=='Up':
            canvas.move(1, 0, -7)
        elif event.keysym=='Down':
            canvas.move(1, 0, 7)
        elif event.keysym=='Left':
            canvas.move(1, -7, 0)
        elif event.keysym=='Right':
            canvas.move(1, 7, 0)
    canvas.bind_all('<KeyPress-Up>', movetriangle)
    canvas.bind_all('<KeyPress-Down>', movetriangle)
    canvas.bind_all('<KeyPress-Left>', movetriangle)
    canvas.bind_all('<KeyPress-Right>', movetriangle)
    canvas.mainloop()

istr()
rect()

If you run this code, then it will be possible to control the second object, but the red rectangle will disappear.
And I need the red rectangle to fall down, but so that the second object can be controlled (istrebitel.gif)
How can I do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yupiter7575, 2021-05-20
@yupiter7575

As long as the main window loop is enabled, all binds will fire. You cannot edit this cycle with your functions. Then the window.update() method comes to the rescue. As a result, you end up with something like this:

canvas.bind(...)
canvas.bind(...)
while play:
    root.update()

Drawing objects must be done before the cycle,

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question