python tkinter上的比例尺移动时,变量不会更新

时间:2018-12-11 10:33:03

标签: python tkinter

每当我运行代码时,当用户与滑动标度(0到100)交互时,变量infection_rate都不会改变。我尝试将IntVar更改为IntVar(),反之亦然,但这没有任何效果。

from tkinter import *
from epidemic import World


class MyEpidemicModel:
    def __init__(self, master):
        self.height = 500
        self.width = 500
        #self.infection_rate = 30
        self.infection_rate = IntVar()
        self.rate = Scale(orient='horizontal', from_=0, to=100, variable=self.infection_rate)
        self.rate.pack()
        self.infection_radius = (self.infection_rate/2)

        self.master = master
        master.title("An Epidemic Model")

        self.label = Label(master, text="This is our Epidemic Model")
        self.label.pack()

        self.canvas = Canvas(master, width = self.width, height = self.height)
        self.canvas.pack()

        self.inputCanvas = Canvas()

        self.start = Button(master, text="Start", command=self.start_epidemic)
        self.start.pack()

    def start_epidemic(self):
        self.canvas.delete('all')
        self.infection_radius = (self.infection_rate/2)
        self.this_world = World(self.height, self.width, 30, self.infection_rate)
        for person in self.this_world.get_people():
            x, y = person.get_location()
            if person.infection == True:
                self.canvas.create_oval(x,y, x+self.infection_radius, y+self.infection_radius, fill="red")
            else:
                self.canvas.create_oval(x, y, x+3, y+3, fill="yellow")
        self.update_epidemic()

错误是:

IndentationError: expected an indented block
PS C:\Users\Eva Morris> & python "c:/Users/Eva Morris/Documents/computing/epidemic/epidemicui.py"
Traceback (most recent call last):
  File "c:/Users/Eva Morris/Documents/computing/epidemic/epidemicui.py", line 76, in <module>
    my_gui = MyEpidemicModel(root)
  File "c:/Users/Eva Morris/Documents/computing/epidemic/epidemicui.py", line 13, in __init__
    self.infection_radius = (self.infection_rate/2)
TypeError: unsupported operand type(s) for /: 'IntVar' and 'int'
PS C:\Users\Eva Morris>

code

Error message

1 个答案:

答案 0 :(得分:0)

设置IntVar后:

self.infection_rate = IntVar()
self.rate = Scale(orient='horizontal', from_=0, to=100, variable=self.infection_rate)

它不是 Python变量

    self.infection_radius = (self.infection_rate/2)
    self.this_world = World(self.height, self.width, 30, self.infection_rate)

一个Tkinter变量-您需要使用.get().set()来访问其值:

    self.infection_radius = (self.infection_rate.get() / 2)
    self.this_world = World(self.height, self.width, 30, self.infection_rate.get())