Python+Tkinter:根据某个 % 值在 canvas 中重绘矩形
Python+Tkinter: Redrawing a rectangle in a canvas based on some % value
我花了很多时间来寻找一种方法来做到这一点...它适用于我正在从事的一个项目,该项目有一百多个 canvas 项需要从文本更新文件。这是一个简单的版本:
我想在按下按钮时更新在 canvas 项中绘制的矩形。 我发现了一个非常糟糕的破解方法,它涉及大量的代码,但我知道必须有更好的方法。
from tkinter import *
class MyGUI:
def __init__(self, root):
frame = Frame(root)
frame.pack()
self.BoxFillPercent = 0 # the canvas items get their % fill from this value
self.changeButton = Button(frame, text='SB', command=self.changeRange)
self.changeButton.grid(row=1, column=1)
self.hAA = Canvas(frame, width=35, height=35, bg='light blue')
self.hAA.grid(row=2, column=2)
self.hAA.create_rectangle(0,0,self.BoxFillPercent*35,35, fill="pink")
self.hAA.create_text(15, 15, anchor='center', text='AA')
def changeRange(self):
self.BoxFillPercent = 0.5
# When I push the button change the fill amount to 0.5
? What do I need to add here to make this work ?
root = Tk()
b = MyGUI(root)
root.mainloop()
我尝试使用更新和 update_idletasks 以及其他一些东西,但我一定遗漏了一些东西。
canvas 上的每个项目都有一个 ID。您可以使用 canvas 的 itemconfig
方法更改项目。
rect = self.hAA.create_rectangle(...)
...
self.hAA.itemconfig(rect, ...)
如果您需要对多个对象应用相同的更改,您可以给这些对象一个公共标签,然后使用该标签代替 id:
rect1 = self.hAA.create_rectangle(..., tags=("special",))
rect2 = self.hAA.create_rectangle(..., tags=("special",))
...
self.hAA.itemconfigure("special", ...)
我花了很多时间来寻找一种方法来做到这一点...它适用于我正在从事的一个项目,该项目有一百多个 canvas 项需要从文本更新文件。这是一个简单的版本:
我想在按下按钮时更新在 canvas 项中绘制的矩形。 我发现了一个非常糟糕的破解方法,它涉及大量的代码,但我知道必须有更好的方法。
from tkinter import *
class MyGUI:
def __init__(self, root):
frame = Frame(root)
frame.pack()
self.BoxFillPercent = 0 # the canvas items get their % fill from this value
self.changeButton = Button(frame, text='SB', command=self.changeRange)
self.changeButton.grid(row=1, column=1)
self.hAA = Canvas(frame, width=35, height=35, bg='light blue')
self.hAA.grid(row=2, column=2)
self.hAA.create_rectangle(0,0,self.BoxFillPercent*35,35, fill="pink")
self.hAA.create_text(15, 15, anchor='center', text='AA')
def changeRange(self):
self.BoxFillPercent = 0.5
# When I push the button change the fill amount to 0.5
? What do I need to add here to make this work ?
root = Tk()
b = MyGUI(root)
root.mainloop()
我尝试使用更新和 update_idletasks 以及其他一些东西,但我一定遗漏了一些东西。
canvas 上的每个项目都有一个 ID。您可以使用 canvas 的 itemconfig
方法更改项目。
rect = self.hAA.create_rectangle(...)
...
self.hAA.itemconfig(rect, ...)
如果您需要对多个对象应用相同的更改,您可以给这些对象一个公共标签,然后使用该标签代替 id:
rect1 = self.hAA.create_rectangle(..., tags=("special",))
rect2 = self.hAA.create_rectangle(..., tags=("special",))
...
self.hAA.itemconfigure("special", ...)