回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我一直在做一个粗略的人口增长计算器类型的项目,只要人口持续增长而没有衰退或降低出生率,它就可以很好地工作。我一直在尝试让一个变量被认为是全局变量,这样就可以在计算总体的函数中读取它。在</p>
<p>但是,我似乎不知道在检查了<code>checkbutton</code>小部件时如何给变量赋值。下面是给你们看的代码:</p>
<pre><code>'''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()
</code></pre>
<p>如果我选中此框,它似乎可以正常工作,但一旦取消选中,该值不会更改。如果我用未选中的值启动它,它将给我一个错误,但是一旦我检查它,就没有错误。检查后,取消选择,没有错误,有什么帮助???在</p>