首页 > 解决方案 > 按下按钮时更新 tkinter 矩形尺寸

问题描述

我希望我的矩形进度条在按下按钮时改变其尺寸,特别是通过将长度增加 10。因为tk.Label我可以使用 a textvariable,但我不知道如何将类似的东西用于矩形坐标。

import tkinter as tk
from tkinter import ttk

def buttonUpdate(width):
    return width.get()+10

root = tk.Tk()

v=tk.IntVar()
v.set(10)

tk.Button(root, text="+10", command=lambda:v.set(buttonUpdate(v))).grid()
tk.Label(root, textvariable=v).grid()

canvas=tk.Canvas(width=140, height=42)
canvas.grid(row=4, column=0, pady=2)
canvas.create_rectangle(0,0,v.get(),10,)

root.mainloop()

我怎样才能实现这样的目标?

标签: pythontkintertkinter-canvas

解决方案


canvas.create_rectangle不支持您希望的变量的使用,但我建议使用这样trace的变量方法来实现您想要的。

def update_rectangle(canvas, r):
    new = canvas.coords(r)
    new[2] = new[2] + 10
    canvas.coords(r, *new)

r = canvas.create_rectangle(0,0,v.get(),10)
v.trace("w", lambda a,b,c: update_rectangle(canvas, r))

root.mainloop()

您可以在此处阅读有关trace方法的更多信息。


推荐阅读