绑定到Tkinter中某个键的“移动对象”功能一次只能移动一个对象,如何使更多对象同时移动?

2024-06-28 19:49:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一个键绑定到一个函数,该函数使椭圆(包括在其他相同椭圆的列表中)移动一定距离。我希望它在每次按下键时都能做出一个新的椭圆移动,如果之前的椭圆移动没有结束,就不会停止

用我的代码,通过按“c”,我创建了一个新的椭圆,随机放置在画布上,并保存在字典中。保存每个新椭圆时,键='compteur','compteur'增量用于每个新创建的椭圆,以确保每个椭圆不是在以前的现有椭圆上创建的。 通过按下“m”,我想在每次按下该键时进行新的椭圆形移动,而前一个移动不会停止

from tkinter import *
import time
from random import *
import time

compteur = 0
dic = {}

w = Tk()
w.geometry('400x400')

c = Canvas(w, width = 400, height = 400)
c.pack()

dic[compteur] = c.create_oval(200,150,250,200,fill = 'pink')
compteur += 1

def create(event):

    global compteur
    b = randrange(300)
    dic[compteur] = c.create_oval(200,b,250,(b+50),fill = 'pink')
    compteur += 1

def move(event):

    rond = dic[randrange(len(dico))]

    if c.coords(rond)[0] == 200:

        for x in range (15):

            c.move(rond,-10,0)
            w.update()
            time.sleep(0.15)         

w.bind('<m>', move)
w.bind('<c>',create)
w.mainloop()

我显然遗漏了一些东西,但作为初学者,我不知道为什么一次只能移动一个椭圆形。奇怪的是,一旦第二个椭圆完成了它的路线,第一个椭圆也开始完成它的路线

谢谢你的帮助:)


Tags: 函数fromimportmovetimedefcreatefill
1条回答
网友
1楼 · 发布于 2024-06-28 19:49:11

我使用列表来保持所有圆圈

move()中,我仅在按下<m>时才从列表中移动最后一个圆

move_other()中,我移动除最后一个圆圈以外的所有圆圈,并在100毫秒(0.1秒)后使用after()运行move_other(),因此它将一直移动

from tkinter import *
from random import *

#  - fucntions  -

def create(event):
    b = randrange(300)
    circles.append(c.create_oval(200, b, 250, (b+50), fill='pink'))

def move(event):
    item = circles[-1]
    c.move(item, -10, 0)

def move_other():
    for item in circles[:-1]:
        c.move(item, -10, 0)

    w.after(100, move_other)

#  - main  -

circles = []

w = Tk()
w.geometry('400x400')

c = Canvas(w, width=400, height=400)
c.pack()

circles.append(c.create_oval(200, 150, 250, 200, fill='pink'))

move_other() # start moving other circles

w.bind('<m>', move)
w.bind('<c>', create)

w.mainloop()

相关问题 更多 >