事件OOPS实现后的Python Tkinter

时间:2013-09-20 12:57:20

标签: python oop tkinter

我是Python的新手,甚至是oops,我想将这个stackoverflow解决方案转换为oops,但它不起作用。我无法弄清楚我应该把它放在哪里,勾选并重置功能以实现这项工作。

#!/usr/bin/python
# -*- coding: iso-8859-1 -*-

import Tkinter
import time

class simpleapp_tk(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.running = None
        self.initialize()

    def initialize(self):
        self.grid()

        self.entryVariable = Tkinter.StringVar()
        self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
        self.entry.grid(column=0,row=0,sticky='EW')
        self.entry.bind("<Return>", self.OnPressEnter)
        self.entryVariable.set(u"Enter text here.")

        button = Tkinter.Button(self,text=u"Click me !",
                                command=self.OnButtonClick)
        button.grid(column=1,row=0)

        self.labelVariable = Tkinter.StringVar()
        label = Tkinter.Label(self,textvariable=self.labelVariable,
                              anchor="w",fg="white",bg="blue")
        label.grid(column=0,row=1,columnspan=2,sticky='EW')
        self.labelVariable.set(u"Hello !")

        self.grid_columnconfigure(0,weight=1)
        self.resizable(True,False)
        self.update()
        self.geometry(self.geometry())       
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)
        self.after(1000, self.tick())
        self.eventbind()

    def OnButtonClick(self):
        self.labelVariable.set( self.entryVariable.get()+" (You clicked the button)" )
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)

    def OnPressEnter(self,event):
        self.labelVariable.set( self.entryVariable.get()+" (You pressed ENTER)" )
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)

    def reset(self, *ignore): 
        self.running = None

    def tick(self, *ignore):
        if not self.running:
            self.running = time.time()
        elif time.time() - self.running > 5:
            print 'I waited 5 seconds...'
            self.running = None
        self.after(1000,self.tick())

    def eventbind(self):
        self.bind('<KEY>',self.reset())
        self.bind('<Button-1>',self.reset())



if __name__ == "__main__":
    app = simpleapp_tk(None)
    app.title('my application')
    app.mainloop()

1 个答案:

答案 0 :(得分:1)

不是将tick - 和rest - 函数传递给after - 和bind - 函数,而是实际调用它们(使用()) ,所以你遇到了stackoverflow。


self.after(1000, self.tick())

应该是

self.after(1000, self.tick)

initializetick中;还有

self.bind('<KEY>',self.reset())
self.bind('<Button-1>',self.reset())

应该是

self.bind('<Key>',self.reset) # note also your type here: it's Key not KEY
self.bind('<Button-1>',self.reset)