首页 > 解决方案 > 当我减小圆圈的比例时,如何删除以前的圆圈?

问题描述

我正在尝试使用 tkinter 来增加圆圈的大小。我面临一个问题,即当我减小圆圈的比例时,前一个圆圈仍然存在。因此,有什么方法可以删除之前的圈子吗?仅供参考,我使用的是 python 2.7.18

from Tkinter import *

root = Tk()
root.title('Elastic collision animation')

canvas = Canvas(root, width=500, height=500)
canvas.pack()

def redraw(a):
    ball_1 = True 
    canvas.delete(ball_1) 
    canvas.create_oval(posn_x, posn_y, posn_x+ball_width+int(a),
                       posn_y+ball_height+int(a), fill='blue')
    canvas.update()  

posn_x = 50
posn_y = 50

ball_width = 10
ball_height = 10

ball_1 = canvas.create_oval(posn_x, posn_y, posn_x+ball_width,
                            posn_y+ball_height, fill='blue')

var = IntVar()
scale_1 = Scale(root, label='mass of ball 1', orient=HORIZONTAL, length=200,
                width=15, from_=1, to= 100, variable = var, command=redraw)
scale_1.pack()



root.mainloop()

问题

标签: pythontkinter

解决方案


试试这个:

from tkinter import *

root = Tk()
root.title('Elastic collision animation')

canvas = Canvas(root, width=500, height=500)
canvas.pack()

def redraw(a):
    global ball_1
    canvas.delete(ball_1)
    ball_1 = canvas.create_oval(posn_x, posn_y, posn_x+ball_width+int(a),
                                posn_y+ball_height+int(a), fill='blue')

posn_x = 50
posn_y = 50

ball_width = 10
ball_height = 10

ball_1 = canvas.create_oval(posn_x, posn_y, posn_x+ball_width,
                            posn_y+ball_height, fill='blue')

var = IntVar()
scale_1 = Scale(root, label='mass of ball 1', orient=HORIZONTAL, length=200,
                width=15, from_=1, to= 100, variable = var, command=redraw)
scale_1.pack()



root.mainloop()

我不知道你为什么有ball_1 = True。我所做的只是删除那条线并将新创建的球 id 分配给ball_1


推荐阅读