Abstract: In this chapter, we will learn the graphical interface programming of python. In python, the default graphical interface is Tkinter (interface). Note that k is in lower case.
1. Programming Environment and running principle if you are using a version earlier than python3.0, the GUI is not installed by default. You need to use yum or apt to install tkinter. It is the default GUI library of python. Based on the Tk toolset, it was originally designed for the tool command language (Tcl.
GUI programming is a C/S architecture and cannot be separated from the window system. The window is a server, and our GUI is a client.
The process of creating and running a GUI is as follows:
1) import the Tkinter Module
2) create top-layer serial port object top (with unlimited names) to accommodate the entire GUI Program
3) create other modules on top
4) associate these GUI modules with the underlying code
5) enter the main cyclic event
The window returned by Tkinter. Tk () is the root window, which is generally named root or top. We can create multiple top-level windows (all other components are placed in this window), but there is only one root.
A component can exist independently or as a container. It is the parent component of the component in the container.
The widget has certain behaviors and actions: the button is pressed, the progress bar is dragged, and the text box is written. These user actions are "events ", the corresponding action for the event is called the callback function ). User operations, generate events, and then execute the corresponding callback. The whole process is called event-driven. Obviously, we need to define the callback function.
Interface Programming involves the creation and layout of components, Association of actions between components, and processing of callback functions.
2. Tk Components
2.1 top-level window import Tkinter
Top = Tkinter. Tk ()
2.2 Other components currently have 15 Tk components:
Button: a Button, similar to a tag, provides additional functions: mouse over, press, release, and keyboard operations
Canvas: Canvas that provides the plotting function
Checkbutton: select a button. You can select any one.
Entry: Text Box
Frame: Framework, a pure container containing other components
Label: note that it is not lable
Listbox: list box
Menu: menu
Menubutton: menu button
Message: message box, which can display multiple lines of text
Radiobuttonscale: single choice button
Scrollbar: scroll bar-scroll through the supported components (text box, canvas, list box, and text area)
Text: text area
Scale: progress bar
Toplevel: top-level, similar to the framework, provides a separate container.
An important aspect of GUI programming is the learning of various controls, including attributes and common methods.
3. Design and Implementation of a GUI program instance 3.1 function design:
We designed such a program to display the files under the directory given a directory;
Double-click the directory to display the files under the directory;
You can use the scroll bar to view files that are no longer in the visual area;
3.2 Interface Design:
3.3 logical design:
1) event Design
Click clear: clear all content in listbox
Click quit to exit
Click list to list the content in the selected directory. If no directory is selected, no processing is performed. If the selected directory is a file, no processing is performed.
Enter a path in the text box to check whether the path is valid. If it is a directory, list it
Double-click a file or folder in listbox to list the contents in the directory.
Drag the scroll bar to display objects in listbox.
2) Callback Function Definition
Clrdir (): clear listbox
DoLs (): list the given dir
3.4 related Code
#!/usr/bin/env python# encoding: utf-8import osfrom time import sleepfrom Tkinter import *class DirList(object):def __init__(self,initdir=None):""" """self.top=Tk()self.title_label=Label(self.top,text="Directory Lister V1.1")self.title_label.pack()self.cwd=StringVar(self.top)self.cwd_lable=Label(self.top,fg='blue',font=('Helvetica',12,'bold'))self.cwd_lable.pack()self.dirs_frame=Frame(self.top)self.sbar=Scrollbar(self.dirs_frame)self.sbar.pack(side=RIGHT,fill=Y)self.dirs_listbox=Listbox(self.dirs_frame,height=15,width=50,yscrollcommand=self.sbar.set)self.dirs_listbox.bind('
',self.setDirAndGo)self.dirs_listbox.pack(side=LEFT,fill=BOTH)self.dirs_frame.pack()self.dirn=Entry(self.top,width=50,textvariable=self.cwd)self.dirn.bind("
",self.doLS)self.dirn.pack()self.bottom_frame=Frame(self.top)self.clr=Button(self.bottom_frame,text="Clear",command=self.clrDir,activeforeground='white',activebackground='blue')self.ls=Button(self.bottom_frame,text="LS",command=self.doLS,activeforeground='white',activebackground='blue')self.quit=Button(self.bottom_frame,text="Quit",command=self.top.quit,activeforeground='white',activebackground='blue')self.clr.pack(side=LEFT)self.ls.pack(side=LEFT)self.quit.pack(side=LEFT)self.bottom_frame.pack()if initdir:self.cwd.set(os.curdir)self.doLS()def clrDir(self,ev=None):#self.cwd.set('')self.dirs_listbox.delete(first=0,last=END)def setDirAndGo(self, ev=None):"""pass:ev: @todo:returns: @todo"""self.last=self.cwd.get()self.dirs_listbox.config(selectbackground='red')check=self.dirs_listbox.get(self.dirs_listbox.curselection())if not check:check=os.curdir#check is the selected item for file or directoryself.cwd.set(check)self.doLS()def doLS(self,ev=None):error=""self.cwd_lable.config(text=self.cwd.get())tdir=self.cwd.get()#get the current working directoryif not tdir:tdir=os.curdirif not os.path.exists(tdir):error=tdir+':no such file'elif not os.path.isdir(tdir):error=tdir+":not a directory"if error:#if error occuredself.cwd.get(error)self.top.update()sleep(2)if not (hasattr(self,'last') and self.last):self.last=os.curdirself.cwd.set(self,last)self.dirs_listbox.config(selectbackground='LightSkyBlue')self.top.update()returnself.cwd.set("fetching dir contents")self.top.update()dirlist=os.listdir(tdir)dirlist.sort()os.chdir(tdir)self.dirs_listbox.delete(0,END)self.dirs_listbox.insert(END,os.curdir)self.dirs_listbox.insert(END,os.pardir)for eachfile in dirlist:self.dirs_listbox.insert(END,eachfile)self.cwd.set(os.curdir)self.dirs_listbox.config(selectbackground='LightSkyBlue')def main():d=DirList(os.curdir)mainloop()if __name__ == '__main__':main()