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

时间:2013-12-03 11:00:36

标签: 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 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()

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

3 个答案:

答案 0 :(得分:0)

在课前使用导入

初始化deathrate

每当更改deathrate的值时:

global deathrate

在更改值之前

。其余的代码工作正常

答案 1 :(得分:0)

为什么要制作一个全局变量呢? 全球变量大多数时候都是坏习惯。

尝试以下方法:

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)
    [...]

现在,您可以通过以下方式访问死亡率和人口增长函数中的变量deathRate:

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 

这称为实例变量。请参阅http://www.python.org/doc/essays/ppt/acm-ws/sld051.htm或python教程(http://docs.python.org/2/tutorial/classes.html)。

问候

答案 2 :(得分:0)

您不需要创建全局变量,并且在选中复选框时不需要执行任何操作。只需在您需要时使用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