Excerpt from python core programming
In this section we will show an example of an intermediate tkinter application, which is a directory tree traversal tool: it will start from the current directory and provide a list of files, and double-clicking any other directory in the list will cause the tool to switch to the new directory , replaces the old list of files with the list of files in the new directory. List boxes, text boxes, and scroll bars are added here, as well as callback functions such as mouse clicks, keyboard presses, and scrolling operations. In fact, the entire application is a combination of a series of controls and functions.
#python 3.6 import os from time import sleep from tkinter import * #A custom class for generating GUI applications class DirList(object): #Constructor def __init__ ( self,initdir= None): self.top = Tk() # Top-level window self.label = Label(self.top,text = ' Find file tool V1.0 ' ) #The first label control self.label.pack() ''' StringVar is not a built-in data type in Python, but an object in the tkinter module. When we use the GUI interface programming, sometimes we need to track the change of the value of the variable to ensure that the change of the value can be displayed on the interface at any time. And Python can't do that. The objects in the Tcl tool are used here. StringVar, BooleanVar, DoubleVar, IntVar all fall into this category StringVar() saves a string type variable, the default value is '' The get() method can get the saved value set() method to set/change the saved value Variable class, some controls such as Entry (appears in this example), Radiobutton, can be directly bound to a program variable by passing in specific parameters, these parameters include: variable, textvariable, onvalue, offvalue, value This binding is two-way: if the variable changes, the controls bound to the variable are also updated. ''' self.cwd = StringVar(self.top) #The second label control. Used to dynamically display some text information self.dirl = Label(self.top,fg = ' blue ' ,font = ( ' Helvetica ' ,12, ' bold ' )) self.dirl.pack() self.dirfm = Frame(self.top) #The first Frame control, a pure container containing other controls self.dirsb = Scrollbar(self.dirfm) #Mainly to provide scrolling function self.dirsb.pack(side = RIGHT, fill = Y) #Scroll bar to the right to fill the entire remaining space ''' A list of options, specifying that the callback function of the list yscrollbar is the set of the scroll bar, and the command callback of the scroll bar is the yview of the list The relationship between the two can be understood in this way: when the Listbox changes (such as using the up and down arrow keys to change the list content), the scroll bar calls the set method to change the position of the slider; When the slider position of the scroll bar changes, the list will call yview to display the new item. Students can cancel the binding and observe the phenomenon by themselves. ''' self.dirs = Listbox(self.dirfm,height = 15,width = 50,yscrollcommand = self.dirsb.set) #Binding operation . This means hooking up a callback function to a key press, mouse action, or some other event. Here, when any item is double-clicked, the setDirAndGo function self.dirs.bind( ' <Double-1> ' ,self.setDirAndGo) will be called self.dirsb.config(command =self.dirs.yview) #This is combined with the yscrollcommand callback of the list control self.dirs.pack(side = LEFT, fill = BOTH) self.dirfm.pack() self.dirn = Entry(self.top,width = 50,textvariable = self.cwd) # Single-line text box. The width is specified; at the same time, the value of a variable type parameter textvariable is set self.dirn.bind( ' <Return> ' , self.doLS) #Binding operation . Here when the Enter key is hit, the function doLS self.dirn.pack() is called self.bfm = Frame(self.top) #Second Frame control # Defines three buttons, each of which calls back a different function, and sets the activation foreground color and activation back color self.clr = Button(self. bfm,text = ' clear ' ,command = self.clrDir,activeforeground = ' white ' ,activebackground = ' blue ' ) self.ls = Button(self.bfm,text = ' search directory ' ,command = self.doLS,activeforeground = ' white ' ,activebackground = ' green ' ) self.quit = Button(self.bfm,text = '退出',command = self.top.quit,activeforeground = 'white',activebackground = 'red') self.clr.pack(side = LEFT) self.ls.pack(side = LEFT) self.quit.pack(side = LEFT) self.bfm.pack() #The last part of the constructor is used to initialize the GUI program, using the current working directory as the starting point. if initdir: self.cwd.set(os.curdir) self.doLS () #Empty function, used to empty cwd, including the current active directory def clrDir(self,ev = None): self.cwd.set('') #Set the directory to be traversed; finally call the doLS function def setDirAndGo(self,ev = None): self.last = self.cwd.get() self.dirs.config(selectbackground = 'red') check = self.dirs.get(self.dirs.curselection()) if not check: check = os.curdir self.cwd.set(check) self.doLS () # Implement the function of traversing directories, which is also the most critical part of the entire GUI program. def doLS(self,ev = None): error = '' tdir = self.cwd.get() #Do some security checks if not tdir: tdir = os.curdir if not os.path.exists(tdir): error = tdir + ' : no such file ' elif not os.path.isdir(tdir): error = tdir + ' : not a folder ' #If an error occurs, the previous directory will be reset to the current directory if error: self.cwd.set(error) self.top.update() sleep(2) if not (hasattr(self,'last') and self.last): self.last = os.curdir self.cwd.set(self.last) self.dirs.config(selectbackground = 'LightSkyBlue') self.top.update() return #if everything is fine self.cwd.set( ' Getting the contents of the target folder... ' ) self.top.update() dirlist = os.listdir(tdir) # actual file list dirlist.sort() os.chdir(tdir) self.dirl.config(text= os.getcwd()) self.dirs.delete(0,END) self.dirs.insert(END,os.curdir) self.dirs.insert(END,os.pardir) for eachFile in dirlist: #Replace the contents of the Listbox self.dirs.insert(END,eachFile) self.cwd.set(os.curdir) self.dirs.config(selectbackground = ' LightSkyBlue ' ) #Main function, application entry. The main function will create a GUI application, and then call the mainloop function to start the GUI program def main(): d = DirList(os.curdir) mainloop () if __name__ == '__main__': main()
running result: