You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter技术问题:如何随滑块/数值框变动重绘圆弧

解决Tkinter滑块/数值框绑定后Canvas圆弧不更新的问题

你的问题出在只在程序启动时获取了一次p1的值,之后p1通过滑块或数值框改变时,之前创建的圆弧坐标不会自动更新——因为create_arc是一次性绘制元素,不会主动监听变量变化。

解决步骤:

  1. 定义回调函数,当p1的值变化时,重新计算圆弧坐标并更新Canvas元素
  2. 将回调函数绑定到p1的变量变化事件上
  3. 初始化时手动调用一次回调,确保圆弧初始位置正确

修改后的完整代码:

import tkinter as tk
from tkinter import ttk
import math

root = tk.Tk()
root.title('Lens')
root.configure(background='#ececec')
root.resizable(False, False)
h = 600
w = 800

myCanvas = tk.Canvas(root, bg="#ececec", height=h, width=w, highlightthickness=0)
y = h/2
x = w/3
r=200

p1 = tk.DoubleVar()

def update_arc(*args):
    # 获取当前p1的数值
    x1 = p1.get()
    # 计算两个圆弧的新坐标
    arc11_coords = (x1 - 1/8*r, y + r*math.sqrt(7)/4, 
                   x1 + 7/8*r, y - r*math.sqrt(7)/4)
    arc12_coords = (x1 - 7/8*r, y + r*math.sqrt(7)/4, 
                   x1 + 1/8*r, y - r*math.sqrt(7)/4)
    # 更新Canvas上的圆弧位置
    myCanvas.coords(arc11, *arc11_coords)
    myCanvas.coords(arc12, *arc12_coords)

# 绑定变量变化事件:p1值修改时触发update_arc
p1.trace_add("write", update_arc)

slider1= ttk.Scale(
    root,
    from_=0,
    to=w/2,
    orient='horizontal',
    variable=p1
)

slider1.pack(ipadx=50, padx=0, anchor=tk.NW, side=tk.LEFT)
spin1 = ttk.Spinbox(
    root,
    textvariable=p1,
    wrap=True,
    width=5,
    from_=0,
    to=w/2,
    increment=.01
)
spin1.pack(anchor=tk.NW, side=tk.LEFT)

# 创建初始圆弧(临时坐标,后续会被update_arc覆盖)
arc11 = myCanvas.create_arc(0,0,0,0, start=90+180/math.pi*math.atan(3/math.sqrt(7)), extent=2*180/math.pi*math.atan(math.sqrt(7)/3), style=tk.ARC)
arc12 = myCanvas.create_arc(0,0,0,0, start=90-180/math.pi*math.atan(3/math.sqrt(7)), extent=-2*180/math.pi*math.atan(math.sqrt(7)/3), style=tk.ARC)

# 手动调用一次update_arc,设置初始位置
update_arc()

myCanvas.pack()
root.mainloop()

关键说明:

  • p1.trace_add("write", update_arc):监听p1的写入事件,滑块拖动或数值框输入修改p1时,自动触发更新函数
  • myCanvas.coords(元素ID, 新坐标):修改Canvas已有元素的位置,这是实现动态更新的核心方法
  • 初始创建圆弧用临时坐标即可,初始化时的update_arc会覆盖为正确位置

内容的提问来源于stack exchange,提问作者qazwsx123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:50:26