- You will want to use classes as your application gets larger. Instead of having to wrap your mind around the entire code, you can concentrate on a class at a time.
- You are not restricted to using only the methods in a class. Your code may utilize external functions or classes to get information or even modify arguments given to them.
- No, that is how would probably display the information. Alternatively, you might use a file to output your results, and it may be possible to print to the console if it is present.
Example:
import tkinter
import random
class 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 present
if __name__ == '__main__':
Application.main()
Alternative to the main
classmethod:
import tkinter
import random
class 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 present
if __name__ == '__main__':
Main()