Python 从checkbutton小部件在Tkinter中分配全局变量

Python 从checkbutton小部件在Tkinter中分配全局变量,python,tkinter,python-2.x,Python,Tkinter,Python 2.x,我一直在做一个粗略的Tkinter人口增长计算器类型的项目,它只适用于人口持续增长,没有衰退或出生率降低。我一直在尝试将一个变量视为全局变量,以便可以在计算总体的函数中读取它 但是,我似乎不知道在选中或不选中checkbutton小部件时如何为变量赋值。下面是代码供大家查看: '''shows human population growth rate through a certain year. It also has an option to include a list of pre

我一直在做一个粗略的
Tkinter
人口增长计算器类型的项目,它只适用于人口持续增长,没有衰退或出生率降低。我一直在尝试将一个变量视为全局变量,以便可以在计算总体的函数中读取它

但是,我似乎不知道在选中或不选中
checkbutton
小部件时如何为变量赋值。下面是代码供大家查看:

'''shows human population growth rate through a certain year.
   It also has an option to include a list of prepared disasters
   that can lower the population.'''

from math import *
from Tkinter import *
import random

class App(Tk):
    def __init__ (self):
        Tk.__init__(self)
        '''Creates the set up for the Tkinter widgets with text on the left side, and the entry values on the right'''
        self.title("Population Growth")

        self.LblOutput = Label (self, foreground = "blue", font = "arial", text = "Enter the year you wish to see the world's population: ")
        self.LblOutput.grid(row = 1, column = 0)

        self.TxtInput = Entry(self)
        self.TxtInput.grid(row = 1, column = 1)

        self.LblOutput2 = Label (self, foreground = "blue", font = "arial", text = "Enter the desired Starting population: ")
        self.LblOutput2.grid(row = 2, column = 0)

        self.TxtInput2 = Entry(self)
        self.TxtInput2.grid(row = 2, column = 1)

        Label(self, foreground = "blue", font = "arial", text = "Turn on Natural Disasters?").grid(row = 3, column = 0)
        self.checkVar = IntVar()
        self.chkCheck = Checkbutton(self, text = "Natural Disasters", variable = self.checkVar, onvalue = 1, offvalue = 0, command = self.mortality)
        self.chkCheck.grid(row = 3, column = 1)

        self.StrtBtn = Button(self, foreground = "black", font = "arial", text = "Begin!", command = self.population_growth)
        self.StrtBtn.grid (row = 6, column = 0)

        self.TxtOutput = Label(self, foreground = "red", font = "gothica" , text = "The Population Is:").grid(row = 7, column = 0)
        self.LblTotal = Label(self)
        self.LblTotal.grid(row = 7, column = 1)

        self.mainloop()

    def mortality(self):
    '''checks to see if the checkmark is checked, if so assigns a random number to deathrate from the range, otherwise deathrate is 0'''
        if self.checkVar.get() == 1:
            deathrate = random.uniform(0.001, 0.00009903)
        elif self.checkVar.get() == 0:
            deathrate = 0
        global deathrate

    def population_growth(self):
        #Using the following equation P=P(subscript = 0)e^rt
        #P(subscript = 0)=initial population, 0 = time; for simplicity = p
        #e = euler's number [approximation]
        #rate_of_growth = rate of growth (found by subtracting crude death rate from crude birth rate
        #time_desired = time (years) that the population is calculated for
        time_desired = int(self.TxtInput.get())
        population_beginning = int(self.TxtInput2.get())
        e_mans_number = 2.71828182845904523536028747135266249775724709369995
        rate_of_growth = 0.01113 - int(deathrate)
        P = population_beginning * ((e_mans_number)**((rate_of_growth)*(time_desired)))
        self.LblTotal["text"] = " %d  people" % P 

def main():
    a = App()

if __name__ == "__main__":
    main()

如果我选中该复选框,它似乎可以正常工作,但一旦取消选中,该值就不会更改。如果我用未选中的值启动它,它将给我一个错误,但一旦我检查它,就没有错误。检查并取消选择后,没有错误,有任何帮助吗

在上课前用导入的初始化
deathrate

无论何时更改
deathrate
的值,请执行以下操作:

global deathrate


更改值之前。代码的其余部分工作正常

为什么要从中生成全局变量? 全局变量在大多数情况下都是一个坏习惯

请尝试以下操作:

class App(Tk):

def __init__ (self):
    Tk.__init__(self)
    '''Creates the set up for the Tkinter widgets with text on the left side, and the          entry values on the right'''
    self.title("Population Growth")
    self.deathRate = random.uniform(0.001, 0.00009903)
    [...]
现在,您可以通过以下方式访问死亡率和人口增长函数中的可变脱氮率:

self.deathrate
例如:

    def mortality(self):
        if self.checkVar.get() == 1:
            self.deathrate = random.uniform(0.001, 0.00009903)
        elif self.checkVar.get() == 0:
            self.deathrate = 0

    def population_growth(self):
        time_desired = int(self.TxtInput.get())
        population_beginning = int(self.TxtInput2.get())
        e_mans_number = 2.71828182845904523536028747135266249775724709369995
        rate_of_growth = 0.01113 - int(self.deathrate)
        P = population_beginning * ((e_mans_number)**((rate_of_growth)*(time_desired)))
        self.LblTotal["text"] = " %d  people" % P 
这称为实例变量。请参阅或python教程()


问候语

选中checkbutton时,您不需要创建全局变量,也不需要执行任何操作。只需在需要时使用checkbutton变量:

def population_growth(self):
    ...
    deathrate = 0
    if self.checkVar.get() == 1:
        deathrate = random.uniform(0.001, 0.00009903)
    rate_of_growth = 0.01113 - deathrate
如果不想将该逻辑放入函数中,只需声明另一个实例变量。使用self.deathrate,而不是使用全局变量:

def mortality(self):
    if self.checkVar.get() == 1:
        self.deathrate = random.uniform(0.001, 0.00009903)
    else:
        self.deathrate = 0

def population_growth(self):
    ...
    rate_of_growth = 0.01113 - self.deathrate

非常感谢,效果不错!我只是想知道是否有一种方法可以让python以逐步的方式进行计算,从0到用户选择的年份,或者它会像计算器一样自动计算出来?