即使我使用tkinter变量,.trace方法和.update方法,我也很难弄清楚为什么下面的代码不会更新。
from tkinter import *
from math import sin, cos, pi
master = Tk()
people_size_var = IntVar()
PeopleSize = Scale(master, from_=1, to=50, bd=3, length=153, variable=people_size_var)
PeopleSize.grid(row=2, column=4, padx=10, pady=5)
people_size_var.set(20)
PeopleSize.config(highlightbackground="white")
def update_canvas(*args):
DisplayFrame.update()
people_size_var.trace("w", update_canvas)
a = 350
b = 140
ellipsePoints = [(a * cos(theta), b * sin(theta))
for theta in (pi*2 * i/number_of_people for i in range(number_of_people))]
DisplayFrame = Canvas(master, bg="white", width=725, height=320)
DisplayFrame.grid(row=0, columnspan=7, column=0, sticky='W', padx=5, pady=5)
for i in range(number_of_people-1):
Bonds = DisplayFrame.create_line(ellipsePoints[i][0]+355+(node_size/2), ellipsePoints[i][1]+155+(node_size/2),
ellipsePoints[i+1][0]+355+(node_size/2), ellipsePoints[i+1][1] +155+(node_size/2),
width=2, fill="black")
for i in range(number_of_people):
People = DisplayFrame.create_oval(ellipsePoints[i][0]+355, ellipsePoints[i][1]+155,
ellipsePoints[i][0]+355 + node_size, ellipsePoints[i][1] + 155 + node_size,
fill="yellow", outline="black", width=2)
master.mainloop()
因此,您可以看到我的代码在Canvas(DisplayFrame)中的这些圆圈之间绘制了一些圆圈和线条。每次people_size_var改变时我都会尝试更新画布,但它不起作用。跟踪确实有效,只是更新功能不起作用。我仍然是所有这些tkinter的新手,所以我真的不知道如何弄清楚代码有什么问题。终端中没有任何错误。
答案 0 :(得分:0)
我认为你不需要在这里使用update()
方法。你已经有一个无限循环运行,主(事件)循环。你可以使用它。
由于你想要在每次缩放时绘制整个东西,你需要在回调中放置绘图内容但是一定不要在每个回调上创建另一个画布,所以你需要把创建画布功能之外的东西,每次都清理画布,在上面绘制新东西。
我认为node_size
是一个常数,number_of_people
随着比例变化。
from tkinter import *
from math import sin, cos, pi
master = Tk()
def update_canvas(*args):
number_of_people = people_size_var.get() #gets scale's value
DisplayFrame.delete("all") #deletes every content from canvas
a = 350
b = 140
ellipsePoints = [(a * cos(theta), b * sin(theta))
for theta in (pi*2 * i/number_of_people for i in range(number_of_people))]
for i in range(number_of_people-1):
Bonds = DisplayFrame.create_line(ellipsePoints[i][0]+355+(node_size/2), ellipsePoints[i][1]+155+(node_size/2),
ellipsePoints[i+1][0]+355+(node_size/2), ellipsePoints[i+1][1] +155+(node_size/2),
width=2, fill="black")
for i in range(number_of_people):
People = DisplayFrame.create_oval(ellipsePoints[i][0]+355, ellipsePoints[i][1]+155,
ellipsePoints[i][0]+355 + node_size, ellipsePoints[i][1] + 155 + node_size,
fill="yellow", outline="black", width=2)
people_size_var = IntVar()
PeopleSize = Scale(master, from_=1, to=50, bd=3, length=320, variable=people_size_var)
PeopleSize.grid(row=0, column=0, padx=10, pady=5)
people_size_var.set(20)
PeopleSize.config(highlightbackground="white")
node_size = 5
DisplayFrame = Canvas(master, bg="white", width=725, height=320)
DisplayFrame.grid(row=0, columnspan=7, column=1, sticky='W', padx=5, pady=5)
people_size_var.trace("w", update_canvas)
master.mainloop()