- 随着应用程序的变大,您将需要使用类。不必全神贯注于整个代码,您可以一次专注于一个类。
- 您不仅限于仅使用类中的方法。您的代码可能利用外部函数或类来获取信息,甚至修改为其提供的参数。
- 不,那可能是显示信息的方式。或者,您可以使用文件输出结果,并且可以打印到控制台(如果存在)。
例:
import tkinterimport randomclass Application(tkinter.frame): @classmethod def main(cls): root = tkinter.Tk() frame = cls(root) frame.grid() root.mainloop() def __init__(self, master=None, cnf={}, **kw): super().__init__(master, cnf, **kw) self.w = tkinter.Label(self, text='Hello, world!') self.w.grid() self.v = tkinter.Button(self, text='Press Me', command=self.click) self.v.grid() self.u = tkinter.Button(self, text='Me Too!', command=lambda: external_mutator(self.w)) self.u.grid() def click(self): self.w['text'] = external_function(3)def external_function(ndigits): return round(random.random(), ndigits)def external_mutator(widget): widget['text'] = external_function(6) print('Hello to you too!') # shown on console if presentif __name__ == '__main__': Application.main()
替代类方法的main
方法:
import tkinterimport randomclass Main(tkinter.Tk): def __init__(self, screenName=None, baseName=None, className='Tk', useTk=1, sync=0, use=None): super().__init__(screenName, baseName, className, useTk, sync, use) frame = Application(self) frame.grid() self.mainloop()class Application(tkinter.frame): def __init__(self, master=None, cnf={}, **kw): super().__init__(master, cnf, **kw) self.w = tkinter.Label(self, text='Hello, world!') self.w.grid() self.v = tkinter.Button(self, text='Press Me', command=self.click) self.v.grid() self.u = tkinter.Button(self, text='Me Too!', command=lambda: external_mutator(self.w)) self.u.grid() def click(self): self.w['text'] = external_function(3)def external_function(ndigits): return round(random.random(), ndigits)def external_mutator(widget): widget['text'] = external_function(6) print('Hello to you too!') # shown on console if presentif __name__ == '__main__': Main()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)