访问gui中的变量

时间:2011-12-09 05:40:38

标签: python class user-interface methods

大家好我有这个代码似乎不起作用。我认为这是因为我的birthCalc方法试图在 init 方法中访问变量。我的问题是我应该如何改变这一点,以便我的程序可以访问那些gui元素及其存储的值。

*请注意,我试图在birthCalc方法的开头访问变量。

class GUI:
    def __init__ (self):
        self.app=Tk()
        bottomFrame=Frame(self.app)
        bottomFrame.pack(side="bottom",pady=10)
        self.app.title("When will you be 1 billion seconds old? ")
        Label(self.app,text="Please enter your birthday").pack()
        Label(self.app, text="Month").pack(side="left",padx=2)
        month=IntVar()
        month.set(1)
        months=range(1,13)
        monthMenu=OptionMenu(self.app,month, *months)
        monthMenu.pack(side="left")

        Label(self.app, text="Day").pack(side="left",padx=2)
        day=IntVar()
        day.set(1)
        days=range(1,32)

        dayMenu=OptionMenu(self.app,day, *days)
        dayMenu.pack(side="left")

        Label(self.app, text="Year").pack(side="left",padx=2)
        year=IntVar()
        year.set(1901)
        years=range(1901,2012)
        yearMenu=OptionMenu(self.app,year, *years).pack(side="left")

        Label(self.app, text="Hour").pack(side="left",padx=2)
        hour=IntVar()
        hour.set(0)
        hours=range(0,25)
        hourMenu=OptionMenu(self.app,hour, *hours).pack(side="left")

        Label(self.app, text="Minute").pack(side="left",padx=2)
        minute=IntVar()
        minute.set(0)
        minutes=range(00,60)
        minuteMenu=OptionMenu(self.app,minute, *minutes).pack(side="left")

        Label(self.app, text="Second").pack(side="left",padx=2)
        second=IntVar()
        second.set(0)
        seconds=range(0,60)
        secondMenu=OptionMenu(self.app,second, *seconds).pack(side="left")

        Button(bottomFrame,text="Calculate", command=self.birthCalc).pack()
        textVar=StringVar()
        textVar.set("You will turn 1 billion seconds old on: ")
        Label(bottomFrame,text=textVar.get()).pack(side="bottom",pady=5)


    def birthCalc(self):
        YEARSEC=31104000 #Values used for converting specified unit into seconds
        MONTHSEC=2592000 #Ex. There are 60 seconds in a minute
        DAYSEC=86400
        HOURSEC=360
        MINUTESEC=60

        year=self.(yearMenu).get() #Get input
        month=self.monthMenu.get()-1    
        day=self.dayMenu.get()-1          #Note that 1 is subtracted because months/days start at 01 (Not 00 as python assumes)
        hour=self.hourMenu.get()
        minute=self.minuteMenu.get()
        second=self.secondMenu.get()

1 个答案:

答案 0 :(得分:2)

__init__函数内部,您应该将元素作为属性添加到类中。 即将monthMenu=OptionMenu(self.app,month, *months)更改为self.monthMenu=OptionMenu(self.app,month, *months)