Python GUI Programming Tkinter example of the directory tree Traversal tool

Source: Internet
Author: User

Excerpt from Python core programming

In this section we will show an example of an intermediate Tkinter application, which is a tree traversal tool: It starts with the current directory, provides a list of files, and double-clicks any other directory in the list, allowing the tool to switch to the new directory and replace the old file list with the list of files in the new directory. A list box, text box, and scroll bar are added here, as well as callback functions such as mouse clicks, keyboard presses, scrolling actions, and so on. In fact, the whole application is a combination of a series of controls and functions.

#Python 3.6ImportOS fromTimeImportSleep fromTkinterImport*#a custom class that generates GUI applicationsclassDirlist (object):#constructor Function    def __init__(self,initdir=None): Self.top= Tk ()#Top-level windowSelf.label = label (Self.top,text ='Find Files Tool V1.0')#First Label ControlSelf.label.pack ()" "Stringvar is not a python built-in data type, but an object within the Tkinter module. When we are programming with the GUI interface, we sometimes need to track the change in the value of the variable to ensure that the value changes at any time to be displayed on the interface. And Python can't do that.        The objects in the TCL tool are used here. Stringvar, Booleanvar, Doublevar, Intvar all belong to this kind of situation stringvar () holds a string type variable, the default value is the "get () method can get the saved value set () method sets/Changes the saved value of the variable class, some controls such as entry (which appear in this example), Radiobutton, can be bound directly to a program variable by passing in a specific parameter, including: variable, textvariable, Onvalue,        Offvalue, value This binding is bidirectional: If the variable changes, the control that is bound to the variable is also updated. " "SELF.CWD=stringvar (self.top)#a second label control. Used to dynamically display some textual informationSelf.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 that contains other controlsSELF.DIRSB = Scrollbar (SELF.DIRFM)#mainly provides the scrolling functionSelf.dirsb.pack (side = Right,fill = Y)#scroll bars to the right to fill the remaining space        " "a list of options, specifying that the callback function for the list Yscrollbar is the set of the scrollbar, and that the command callback of the ScrollBar is the list of Yview so that the relationship between the two is understood: when the listbox changes (such as using the UP and DOWN ARROW keys to change the contents of the list)        , the scroll bar calls the Set method to change the position of the slider, and when the slider position of the scrollbar changes, the list calls Yview to present the new item.        Students can cancel the binding and observe the phenomenon on their own. " "Self.dirs= Listbox (self.dirfm,height = 15,width = 50,yscrollcommand =self.dirsb.set)#The bind operation. This means linking a callback function to a keystroke, mouse action, or some other event. Here, when you double-click any entry, the Setdirandgo function is calledSelf.dirs.bind ('<Double-1>', Self.setdirandgo) self.dirsb.config (Command=self.dirs.yview)#This is combined with the Yscrollcommand callback for the list controlSelf.dirs.pack (side = Left,fill =BOTH) self.dirfm.pack () Self.dirn= Entry (self.top,width = 50,textvariable = SELF.CWD)#A single-line text box. The width is specified, and a variable type parameter textvariable value is set .Self.dirn.bind ('<Return>', Self.dols)#The bind operation. Here, when hitting the ENTER key, call the function DoLSself.dirn.pack () SELF.BFM= Frame (Self.top)#a second frame control        #defines three buttons, each of which callback a different function, and sets the activation foreground color, the active post colorSELF.CLR = Button (Self.bfm,text ='Clear', command = Self.clrdir,activeforeground =' White', Activebackground ='Blue') Self.ls= Button (Self.bfm,text ='Search Catalog', command = Self.dols,activeforeground =' White', Activebackground ='Green') Self.quit= Button (Self.bfm,text ='Exit', 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, used to initialize the GUI program, takes the current working directory as the starting point.         ifInitdir:self.cwd.set (Os.curdir) self.dols ()#empty function to empty the CWD, containing the current Active Directory    defClrdir (Self,ev =None): Self.cwd.set ("')        #sets the directory to traverse, and finally calls the DoLS function    defSetdirandgo (Self,ev =None): Self.last=Self.cwd.get () self.dirs.config (Selectbackground='Red') Check=Self.dirs.get (Self.dirs.curselection ())if  notCheck:check=os.curdir self.cwd.set (check) self.dols ()#It is the most critical part of the whole GUI program to implement the function of traversing directory.     defDoLS (Self,ev =None): Error="'Tdir=Self.cwd.get ()#carry out some security checks        if  notTdir:tdir=Os.curdirif  notos.path.exists (tdir): Error= Tdir +': no this file'        elif  notOs.path.isdir (tdir): Error= Tdir +': Not a folder'        #If an error occurs, the previous directory will be reset to the current directory        ifError:self.cwd.set (Error) Self.top.update () Sleep (2)            if  not(Hasattr (Self,' Last') andself.last): Self.last=os.curdir Self.cwd.set (self.last) self.dirs.config (Selectbackground='Lightskyblue') self.top.update ()return        #If everything is fineSelf.cwd.set ('getting target folder contents ...') self.top.update () dirlist= Os.listdir (Tdir)#get the actual file listDirlist.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.par DIR) forEachfileinchDirlist:#Replace content in a ListBoxSelf.dirs.insert (end,eachfile) self.cwd.set (os.curdir) self.dirs.config (Selectbackground ='Lightskyblue')#main function, application portal. The main function creates a GUI application, and then calls the Mainloop function to start the GUI programdefMain (): D=dirlist (Os.curdir) mainloop ()if __name__=='__main__': Main ()

Operating effect:

Python GUI Programming Tkinter example of the directory tree Traversal tool

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.