Getting started with Python: Hello
from Tkinter import *class Application(Frame): def say_hi(self): print 'hello' def createWiegets(self): self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.pack({"side":"left"}) self.hi_there = Button(self) self.hi_there["text"] = "hello" self.hi_there["command"] = self.say_hi self.hi_there.pack({"side":"left"}) def __init__(self,master=None): Frame.__init__(self,master) self.pack() self.createWiegets()root = Tk()app = Application(master = root)app.mainloop()root.destroy()
This code shows how to use Python to create a graphical interface. The graphical interface library Tkinter in python is used.
Import the corresponding module: from Tkinter import * defines a class that inherits the Frame
class Application(Frame): def say_hi(self): print 'hello' def createWiegets(self): self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.pack({"side":"left"}) self.hi_there = Button(self) self.hi_there["text"] = "hello" self.hi_there["command"] = self.say_hi self.hi_there.pack({"side":"left"}) def __init__(self,master=None): Frame.__init__(self,master) self.pack() self.createWiegets()
Define controls
def createWiegets(self): self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.pack({"side":"left"}) self.hi_there = Button(self) self.hi_there["text"] = "hello" self.hi_there["command"] = self.say_hi self.hi_there.pack({"side":"left"})
Create an object and use
root = Tk()app = Application(master = root)app.mainloop()root.destroy()
In the code snippet above, root represents the window container. We create an Application object, specify its window container, enable the Message Queue loop, and finally destroy the window.