Location via proxy:
[ UP ]
[Report a bug]
[Manage cookies]
No cookies
No scripts
No ads
No referrer
Show this form
Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
92 views
How To Build A Python GUI Application With Wxpython
How to Build a Python GUI Application With wxPython
Uploaded by
Marcos Luis
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save How to Build a Python GUI Application With wxPytho... For Later
Download
Save
Save How to Build a Python GUI Application With wxPytho... For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
92 views
How To Build A Python GUI Application With Wxpython
How to Build a Python GUI Application With wxPython
Uploaded by
Marcos Luis
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save How to Build a Python GUI Application With wxPytho... For Later
Carousel Previous
Carousel Next
Save
Save How to Build a Python GUI Application With wxPytho... For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 17
Search
Fullscreen
How to Build a Python GUI Application With wxPython by ike Dscoll ® 18Comments (medina) MarkasCompleted share Table of Contents + Getting Started with wxPython installing waPython © Definition of a Gut © EventLoops + Creating Skeleton Application 9 Widgets © Absolute Positioning Sizer (Oynamic Sizing) Adding an Event + Coeatinga Working Application © Designing the User Interface Creating the User interface © Make a Functioning Application + Conclusion + Further Reading © momoveads “There are many graphical user interface (GUI) toolkits that you can use with the Python programming language. The big three are “inter, waPython, and Pyar. Each of these toolkits will work with Windows, macOS, and Linux, with PyQt having the additional ‘capability of working on mobile ‘Agraphical user interfaces an application thathas buttons, windows, and lots of other widgets thatthe user can use to interact ‘with your application. & good example would be a web browser. thas buttons, tabs, and a main window where al he content loads.In this article, you'l learn how to build a graphical user interface with Python using the wxPython GUI toolkit. Here are the topics covered: + Getting Started with wrPython + Definition of a GUI + Creating a Skeleton Application + Creating a Working Application Lets start learning! Free Download: Geta sample chapter from Python Tricks: The Book that shows you Python's best practices with simple ‘examples you can apply instantly to write more beautiful + Pythonic code, Getting Started With wxPython The wxPython GUI toolktis a Python wrapper around a Cr+ library called waWidgets. The initial release of wxPython wasn 1988, so wxeython has been around quite along time. waPython’s primary difference from ather toolkits, such as Py@t or Tkinter, is that wePython uses the actual widgets on the native platform whenever possible. This makes wxPython applications look native to the operating system that s running on. PyQt and Tkinter both draw their widgets themselves, which is why they don’t always match the native widgets, although PyQtis, very clase Thisis notto say that waPython does not support custom widgets. Infact, the waPython toolkit has many custom widgets Included withit, along with dozens upon dozens of core widgets. The waPython downloads page has a section called Extra Files ‘that is worth checking out Here, theresa download ofthe wxPython Demo package. This isa nice litle application that demonstrates the vast majority of| ‘the widgets that are included with wxPython, The demo allows a developer to view the code in one tab and run tina second tab. You can even edit and re-run the code inthe demo to see how your changes affect the application. © Removes Installing wxPython ‘ouwillbe using the latest waPython fortis cle whichis waPython 4 alo known as the Phoenix release, The wnPython 3 and waPython 2 versions are uit only for Python 2. When Robin Dunn the primary maintainer af waPython, crated the wPython release, he deprecated a lotof aliases and cleaned up alot of code to make waython more Pythonic and easier to You wil want to consult the following links fyou are migrating rom an older version of wxPython to waPython 4 (Phoenix: * Classic vs Phoenix + wnPython Project Phoenix Migration Guide The wxPython 4 package is compatible with both Python 2.7 and Python 3. You can now use pip to install wxPython 4, which was not possible inthe legacy versions of wxPython. You can do the following, tolinstall ton your machine: Shel $ pip instald wasython Note: On Mac OSX you willneed a compiler installed such as XCode forthe install to complete successfully Linux may also require yout install some dependencies before the pip installer will work correctly,For example, | needed to instal freeglut3-dev, libgstreamer-plugins-base0.10-dev, and libwebkitgtk 3.0-dev on Xubuntu to get itt install, Fortunately, the error messages that pip displays are helpful n figuring out what is missing, and you can use the prerequisites section on the waPython Github paget help you find the information you need ifyou want ta install wxPython on Linux There are some Python wheels avaliable for the most popular Linux versions that you can find in the Extras Linux section with both G12 and GTK3 versions. To install one ofthese whee!s, you would use the following commané: Shel § pip install -U =f htspe://extras.onpython.ong/hxbythoné/extae/Tinux/k3/Ubuntue38.@6/ sxPython Be sure you have modified the command above to match your version of Linux Definition of a GUI ‘Aswas mentioned inthe introduction, a graphical user interface (GUI isan interface that is drawn on the screen forthe user to imeractwith User interfaces have some common components: ‘+ Main window + Menu + Toolbar + Buttons + Text Entry + Labels Allof these items are known generically as widgets. There ae many other common widgets and many custom widgets that ‘waPython supports. A developer will take the widgets and arrange them logicaly on 2 window for the user to interact with Event Loops ‘Agraphical user interface works by waiting fr the user to do something, The something's called an event. Events happen when ‘the user types something while your application isn focus or when the user uses their mouse to press a button or other widget. Underneath the covers, the GUI toolkit is running an infinite loop that i called an event loop. The event loop just waits for events to occur and then acts on those events according to what the developer has coded the application to do. When the application doesn't catch an event, it effectively ignores thatt even happened When you are programming a graphical user interface, you will want to keep in mind that you will need to hook up each of the widgets to event handlers so that your application will do something. There is a special consideration that you need to keep in mind when working with event loops: they can be blocked. When you block an event loop, the GUI will become unresponsive and appear to freeze to the user. ‘Any process that you launch in 2 GUI that wil take longer than a quarter second should probably be launched asa separate ‘thread or process. This will prevent your GUI from freezing and give the user a better user experience. The wxPython framework has special thread-safe methods that you can use to communicate back to your application to leit know that the thread is finished orto give tan update Let's create a skeleton application to demonstrate how events work © remove ndsCreating a Skeleton Application ‘An application skeleton in a GUI contexts a user interface with widgets that don't have any event handlers. These are useful for prototyping, You basically just create the GUI and present ito your stakeholders for sign-off before spending alot of time on the backend logic Let's start by creating a Helio worsa application with wxPython Prthon app = we.850() frane = wx.Frame(parenteRone, tite Hello World") frane. show) app. main.oop() Note: Mac users may get the following message: Ths program needs access tothe screen Please run witha Framework build ‘of python, and only when you are logged in on the main display of your Mac. you see this message ane you are not running in avirwaleny, then you need to run your application with pythenw instead of python. Ifyou are running vPython from within a virtualeny, then see the waPython wiki forthe solution. In this example, you have two parts: wx.spp and the wx. rane. The we. App is wxPython’s application object andisrequited for running your GUI. The wx. App starts something called .sinL.oop(). This is the event loop that you learned about in the previous section The other piece of the puzzle iswx-Frave, which wll create a window forthe use to interact with. In this case, you told wxPython ‘hat the frame has no parent and that its titleisHello world, Here is whatit looks like when you run the code: Note: The application wil look diferent when you run it on Mac or Windows. By default, awx.Frane wil include minimize, maximize, and ext buttons along the top. You won't normally create an application inthis manner though. Most wxPython code will require you to subclass the we.Frane and other widgets so that you can getthe full power ofthe toolat Let's take a moment and rewrite your code asa class: Pron lass myrane(u Feane) def _init_ (ei: Tiper()c_indt_(parent-None, tHtle-el To World") sel¥.showt) Frame = tyFrane() app.matntoop()You can use this code as a template for your application. However this application doesn't do very much, so lets take 2 moment ‘0 earn litle about some ofthe other widgets you could add Widgets The waPython tolkt has more than one hundred widgets to choose from, This allows youtocreaterich applications, butt can alsobe daunting tying to figure out which widget to use. Tiss why the wAPython Demos helpful, sit has a search ite that you can use to lp you find the widgets that might apply to your project. Most GUI applications allow the user to enter some text and press a button. Let's go ahead and add those widgets: Python lass WyFrane(w Foon). det _init_ (seit) Siner()-_intt_{parent-tore, 131 panel = we-Poral(sei*) selé.text_etrl = saTextctel{panel, sy_btn = we Button{panel, Label~'Peess Me, pos-(S, 55)) sel¥. show) “app = wap) rane = HyFrane() pp Maintoop() \When you run this code, your application should look tke this: The fist widget you need to add is something called wx. Pane. This widgets not required, but recommended, On Windows, you are actually required to use a Panel so thatthe background color ofthe frame isthe right shade of gay. Tab traversal is disabled without a Panel on Windows. \When you ada the panel widget toa frame and the panelis the sole child ofthe frame, it will automatically expand to fil the Franve with tell The next stepis to add a wx. Yextctet to the panel. The first argument for almost all widgets is which parent the widget should go beon top of the panel, so itis the parent you speci. conto. In ths case, you want the text control and the button t ‘You also neec to tell waPython where to place the widget, which you can de by passing in position va the pos parameter. In waPython, the origin location is 0,0) which i the upper left corner of the parent So forthe text control, you tell wxPython that ‘you want 1 position is top left cornerS pixels from the left (x) and 5 pixels from the top Then you add your button to the panel and give it label. To prevent the widgets from overlapping, you need to setthey- coordinate to 55 for the button's position, © aenoveatsAbsolute Positioning \When you provide exact coordinates for your widgets position, the technique that you used is called absolute positioning. Most GUI tootkts provide this capability, but its not actually recommended. ‘As yout application becomes more complex, it becomes dificult to keep trac ofall the widget locations and ifyou have to move ‘the widgets around, Resetting all those positions becomes a nightmare. Fortunately all modern GUI toolkits provide 2 solution for this, whichis wht you will learn about next Sizers (Dynamic Sizing) ‘The wxPython toolkit includes sizers, which are used for creating dynamic layouts, They manage the placement of your widgets for you and will adjust them when you resize the application window. Other GUI toolkits will refer to sizes as layouts, whichis what Pyat does. Here are the primary types of sizers that you will se used most often Let'sadd awe. boxstzer to your example and see if we can make it work abit more nicely: Pron class myFrane(w. Frame) def _init_(s0I0) Siver();_init_{parentevore, thtles'Hello world") panel ~ weParel(sei*) fy_sizer = en BoxSizer (ot. VERTICAL) selfstext_ctrl = wa Textctrl(parel) syisizer.Ado(sol4-text_ctrl, 8, WALL | 4x ARD, 5) sy_btn ~ wx button{panal, Label~' ess He") rypsizer.Aade(ay ben, @, we.ALL | W-CENTER, 5) panel. Setsszer(ay sizer) sel¥.show() rane = tyFrane() app.maintoop() Here you create an instance ofa wx. SoxStzer and pass wx VERTICAL, Which isthe orientation that widgets are added to the sizer. In this case, the widgets willbe added vertically, which means they wll be added one ata time from top to bottom. You may also seta BoxSizer’s orientation to wx. HoerZoNTAL. When you do that, the widgets would be added from lft to right. To ade a widget toa sizer, youwill use .ads(.Itaccepts upto five arguments + seindow (the widget) + 628 + border The window arguments the widget to be added while proportion sets how much space relative to other widgets in the sizer this, particular widget should take, By default its zero, which tells waPython to leave the widget atts default proportion. The third argumentis fag. You can actually pass in multiple flags you wish as long as you separate them witha pipe character |. The wxython toolkit uses | to add flags usinga series of bitwise ORs.In this exemple, you add the text control withthe wx. Att and wx. exeane flags. The we. ALL flag tells wxPython that you want to add a border on all sides ofthe widget while wx.cxoano makes the widgets expand as much as they can within the sizer. Finally you have the boréer parameter, which tells wxPython how many pixels of border you want around the widget. The tserdate parameter is only used when you want to do something complex with your sizing ofthe widget and is actually quite rare to seein practice. ‘Adding the button to the sizer follows the exact same steps, However, to make things abit more interesting, | went ahead and switched out the we xravo flag for we. CENTER So thatthe button would be centeree on-screen, ‘When you run this version ofthe code, your application should look like the following oe ota Mt If you'd like to learn more about sizers, the wxython documentation has anice page on the topic. © aemoveats Adding an Event ‘While your application looks more interesting visually it still doesn't really do anything. For example, ifyou press the button, nothing really happens Lets give the button ajob: Pron class WyFrane(w. Fran) det _init_(seit) Siner();—init_tparenteore, t8€1 panel ~ wx-Parei(se!#) sy_s8zer ~ we BoxSSzer(oe VERTICAL) self tent_ctrl — wa Textctr (panel) sy_sizer Ado(oel? text_ctrl, 8, WALL | wx.BOAD, 5) sylbtn = we button( panel, Tabet’ Poss Ho") fylbtn.bind(wn,€V1bUTTOH, se1F.0n press) rysizer.Adé(ay btn, @, weALL | w-CENTER, 5) panel. Setsizer(ay_sizer) ele. Show) ete Wort") ef on_press(self, event) value ~ sel text_etrl.Getvalue() Prine("You didn't enter anything print(#"You typed: “(value}"") Gop wet rane = tyFrane() Main oop() The widgets in wxPython allow you to attach event bindings to them so that they can respond to certain types of events.Note: The code block above uses fstrings. You can read all about them in Python's F-String for String Interpolation and Formatting, ‘You want the button to do something when the user presses. You can accomplish this by calling the button’s .sina() method, ‘ind() takes the event you want to bind to, the handler to call when the event happens, an optional source, and a couple of optional ids In this example, you bind your button objec to the wx. v"_BUTTOW event an Litto call on_press() when that event gets fired. ‘an event gets “fired” when the user does the event you have bound to. In this case, the event that you set ups the button press event, x EVT_SUTTON, on_press() acceptsa second argument that you can call event. This isby convention, You could callit something else ifyou wanted to, However, the event parameter here refers tothe fact that when this method i called, its second argument should be an event object of some sort. ‘Within .on_press(), you can get the text controls contents by calling its Getvalue() method. You then printa string to stdout depending on what the contents of the text controls. Now that you have the basics out ofthe way, let's learn how to create an application that does something usefull Creating a Working Application The first step when creating something new is to figure out what you want to create In this case, have taken the liberty of ‘making that decision for you. You will earn how to create a MPS tag editor! The next step when creating something new isto find ‘out what packages can help you accomplish your task l¥you do a Google search forPytnon #63 tagging, you will finé you have several options I tied out a couple ofthese and decided that eyeD3 had a nice API that you could use without getting bogged down with the 'MP3's [D3 specification, You can install eyeDS using pip, like this: shal a $ php snstald eyed When installing this package on macOS, you may need to install 1sbeagic using brew, Windows and Linux users shouldn't have any isues installing eyeD3, Designing the User Interface ‘When it comes to designing aninterface its always nce ta ust kind of sketch out how you think the user interface should tok, ‘ouwilineed oe ableto do the folowing + Openup one or more MPS files + Display the current MP3 tags + Egitan MP3 tog Most user interfaces use a menu or a button for opening fies or folders. You can go witha File menu for this. Since you wll probably want to see tags for multiple MP3 files, you will eed to find a widget that can do ths na nice manner. Something that is tabular with columns and rows would be ideal because then you can have labeled columns for the MP3 tags The wxPython toolkit has afew widgets that would work for this, with the top two being the following: # wxstistctetYou should use ws. tis ‘ein this case as the evi widgets overkill, and frankly its also quite bit more complex. Finally, you need a button touse to edita selected MP3's tg. Now that you know what you want, you can draw itup: [Protea Ear Basch ye et Sounds Nour be New mac crow fone tawtit |re Feet Ct The Daepnat The illustration above gives us an idea of how the application should look, Now that you know what you want to doi’ time to code! © aenoveats Creating the User Interface There are many diferent approaches when it comes to writing a new application. For example, do you need to follow the Model. View-Controller design pattern? How do you split up the clases? One class per ile? There are many such questions, and as you get more experienced with GUI design, you'l know how you want to answer them, In your case, you really only need two classes: + Awx.panel class + Run. frame class You could argue for creating a controller type module as well, but for something lke this, you really do not need it Acase could alse be made for putting each class into its own module, but ta keep it compact, you wil create a single Python file forall of your code. Lets start with imports and the panel cass Pronnport eyet3 lass HptPaned (wx. Panel): def _init_(seif, parent) Tiver()._init_tparent) sain_si20r ~ wi BoxSiz0 (wx VERTICAL) selrowobisict = self ldstetrd = wx Listetra( Fy size-(-1, 180), Styles LC REPORT |e SORDER_ SUNKEN > self. List trl tnsertcolumn(@, ‘Artist, wigth-14a) self. list_etrlInsertcolumn(1, ‘Albuns width-140) self. 1istetrlInsertcolumn(2, “Tiele", widths200) sain sizer Ada(seit List_ctrl, 8, WALL | wx 00890, 5) sait_putton = wx.putzon(self, Tabel= Foie") eait_button-Bind(ux.€VT_BUTTON, sel*.on edit) ain_sizer Ago(edSt button, ©, wx ALL | Wx.CENTER, 5) sole SetStzer(nain sizer) Gee on_edit(seif, event) print(" in on’eait'y ef update_np2_listing(sel*, folders print¢Felder_path) Here, you import the eyees package, Python's glob package, and the we package for your user interface. Next, you subclass swx-Panet and create your user interface. You need a dictionary for storing data about your MP3s, which you can name row_obt.¢ Then you create awe.ListCtrt and sett to report mode x.Lc_ssPoet) witha sunken border (x. doRoeR_ sunken). The list control can take on 2 few other forms depending on the style fag that you pass in, but the report fagis the most popular Tomake the Listctrz have the correct headers, you will need to call .rnsertCotuan() for each column header. You then supply ‘he index of the column, its abel, and how wide in pixels the column shoul be. The last step isto add your east button, an event handler, and a method. You can create the binding to the event and leave the ‘method that it calls empty for now. Now you should write the cade forthe frame: thon lass Wrane(w. rane): def _init_ (aif) Tipe _inst_tparentnore, fetes Hp? Tag esitor") sel¢spanel = wp3Panel (sf) sel. Show) “app = wx.app(Faise) rane = wpsfrane() app.matn.oop() This lassis much simpler than the frst one in that all you need to dois set the tte ofthe frame and instantiate the panel class, tp3Panel. When you ae all dane, your user interface should look like this:Mp3 Tag Ete ‘The user interface looks almost right, ut you don't have a File menu. This makes itimpossible toad MP3s tothe application and edt their tags! Lets fxthat now, Make a Functioning Application The frst step in making your application work sto undate the application so that thas a File menu because then you can add MP3 lls to your creation. Menus ae almost always added tothe we.Frane class, so thats the class you need to modi. Note: Some applications have moved away from having menus in their applications. One ofthe fist to do so was Microsoft Office when they added the Ribbon Bar. The waPython toolkit has a custom widget that you can use to create ribbons in ve. 118. rbon he other type of aplication that has dropped menus of late are web browsers such as Google Chrome and Mozilla Firefox, They just use toolbars nowadays. Let's learn how to add @ menu bar to our application: Pron lass Mpafrane(. rane): det _init_(oare) Frame. init_(selé, parentoone, hele ip} Tag far") self. panel = HpaPanel (Serf) self.eneate_nens() sel¥ Show) of ereate_nenutsel*) sen par — ex MenuBar() Fleapeny = we nen¥) pen_folder_nens Sten = #5 ‘TD_AiWY, “Gpen Toler", enw. Aopend( > rnenu_bar.Append(¢ale_venu, ‘Ae2)6") selesaind¢ > Sele. Setenubar (menu ar) det on_open_folder(sei6, rent) fig - we.0irbialog( slr, title, ‘style 00_DEFAULT_ST¥LE) 16 dig. sSpowoeal() = we.10_06 cif. panel update} Listing(aig.GetPath()) aig. vestroy()Here, ou add a call to .create_nanu() within the class's constructor. Then in create_nenu() isel, you wll create @wr.Fenusar instance and 2wx.senuinstance. To adé a menu item to a menu, you call the menu instance’s Append) and pass i the following: + Aunique identifier ‘The abel forthe new menu item + Ahelp string Next, you need to add the menu to the menubar, so you will need to call the menubar's.aapend() lt takes the menu instance anc ‘the label for menu. This labels abit odd in that you called it rite instead of rile. The ampersand tells waPython to create 3 keyboard shortcut of alt + F to open theriie menu using ust your keyboard, Note: Ifyou would ike to add keyboard shortcuts to your application, then you will want to use an instance of sox. acceler -rale to create them. You can read more about Accerator Tables in the wxPython documentation. To create an event binding, you will ned to call se1¢. ind), which binds the frame to wx. cv"_Mew. When you use self.ind() for a menu event, you need to not only tell wxPython which handler to use, bt also which source to bind the handler to. Finally, you must call the frame's setenusar() and passit the menubar instance fo ito be shown tothe user. Now that you have the menu added to your frame, let's go over the menu items event handler, which’ reproduced again below: Pron det on open foluer(selt, event): choose 9 directory.” 4g = se Dsrotalog(sels, #itie, stytene 00, DEFAULT STYLE) 16 lg. showedal() == we: 100 se1F.panal-upeate_np}_Listing( ae. GetPath()) ig. vestroy() Since you want the user to choose a folder that contains MP3s, you will want to use wsPython's wx, oirbislog, The wx.0irbialog allows the user to only open directories. You can set the dialog's title and various tye flags To show the dialog, you will need to call stowtoss1(), This will cause the dialog to show modally, which means that the user won't be able to interact with your main application while the dialog's shown, the user presses the dialog's OK button, you can get the user's path choice via the dialog's cet en). You will want te pass ‘hat path to your panel class, which you can do here by calling the panel's update ep3_histing() Finally you need to close the dialog, To close dialog, the recommended method isto callits vestroy() Dialogs do have 3 .closet) method, but that basically ust hides the dialog, and it wll not destroy itself when you clase your application, which can lead to werd issues such as your application now shutting down propery.’ simpler to call .estroy() on the dialog to prevent thisissue Now let's update your tp2Panel class. You can start by updating update pp3_Aseting() thondet vadate_np3_Listing(seit, Folder_path) self List_¢trl.Chearall@ Self 1Ast cert trsertcolum(a, “Actist, width-340) Self. List ctrl trsertcoluen(2, ‘albus’, wisth-240) self Hstetrd-tnsertCoturn(2, “Istie", wieth=200) Sself.List_eerl ansertcolum(3, ‘Year’ wiéth-200) 193s = glob.glob(folder_path + °/*.963°) rp3.obects = (] pa_object = eyeds. Load(aps) sels. list ctrl Insererten(index, noa.onject. tag artist) self. 18st trl SetTter(index, 4, np2_aject. tag. bn) self. list str] SetTten(index, 2, no2_oaject. tag. title) p3_objects.append(np3_object) selF-ro_obj sietLindex] = mp3object Here you set the current directory tothe specified folder and then you clear the lst control. This keeps the lst control fresh and only showing the MP3s that you are currently working on. That also means that you need to re-insertall the columns again Next you'll want to take the folder that was passed in and use Python's glob module to search for MPS files, Then you can loop over the MP3s and turn them into eyeds objects. You can do thisby calling the oad) of eyed3. Assuming that ‘the MP3s have the appropriate tags already, you can then add the arts, album, and title ofthe MP3 tothe ist control Interestingly, the method of adding a new row toa ist control object is by calling .zasertzten() fr the fist column and {cent for al the subsequent columns. The last step isto save off your MP3 object to your Python di nary, row_obj_ dict. Now you need to update the .on_edit() event handler so that you can edit an MP3‘ tags Pron ot on_e8it (seit, event): election - self Tst_etrl.GetFocuseélten() 16 selection sp) = sel*-row cbf atet[ selection} fig ~ Eeteosalogtop2) 4g. showods2() sel upeate_ap)_Isting(soif current folder ig. estroy() The first thing you need to dois get the user's selection by calling the lst contrl’s .GetFocusedTten() the user has not selectes anything in the list contro, it will return -2, Assuming thatthe user did select something, you will ‘want to extract the MP3 object from your dictionary and open a MPS tag editor dialog. This willbe a custom dialog that you will Use to et the artist, album, an ttle tags of the MP3 ile ‘As usual, show the dialog modally. When the dialog closes, the last two linesin-or_eatt() will execute. These two lines wil Update the list control soit displays the current MP3 tag information thatthe user just edited and destroy the dialog, Creating an Editing Dialog The inal piece ofthe puzzles creating an MPS tag editing dialog. Fr brevity, we will skip sketching outthis interface asit isa series of rows that contains labels and text controls. The text controls should have the existing tg information pre-populated within them. You can create a label forthe text controls by creating instances ofwx.statictext. ‘When you need to create a custom dialog, the wx.otalog class is your fiend, You can use that to design the editor:Prthon class e6ttoiatogtexoialog) et _init_(seif, mp3) Hele = Feeiting “{ap3.tag tithe) super()._init_j{parent-vone, 1381 selésnps > mp3 selfomain_sizer ~ wx BoxStzer(ax. VERTICAL) selfcarciat = wa.Textctel( S006, valoesrenfap3.tag.antist) selfvade widgeta( Arist", self. areist) selésalbym = we Textctea( olf, value-sel 993.498 alba) selt.adé midgets(Albue", sel¢.albue) self title = we Textcenn( Self, valuecseif.9p3.tag.t&tle) seltsadé wtdgers( ‘Title’, sel¢.title) benaizer = wr aoxsizer() save_ben = wx.Button( self, Label~'save') save_ben.Bind(wx.€VT_SUTTON, seif.on save) ben sizer Adatsave bin, 8, wall, 5} ben_sizer Aden. utzon oly Adee TDLOONEEL), 8 MHLALL, 5) selt.nain_sizer.taa(ben sizer, 0, we CENTER) sele.setsizer(sei¢.nain_sizer} astie) Here you want to stat off by sub-ciassing wx.biaiog and givingita custom ttle based on the title ofthe MP3 that you are editing, Next you can create the sizer you want to use and the widgets. To make things easier, you can create a helper method called saa_widgets() foradding thewx.staticText widgets as rows with the text control instances. The only other widget here isthe ‘Save button, Let's write the add_widgets method next: Prthon det odd_wbdgets(selé, label text, text ctrl) row si2er = x doxsizer (we HORIZONTAL) Isbel = wx Statictoxt(self, Tabel-label_sext, sizes(58, -1)) row sizer.Adé(label, @&, weAtL, 5) owaizer.Add{text ctrl, 2, we ALL | wx. EXPAND, 5) selvsnain_sizer.Add(ron sizer, 0, wx EXPAND) 2a9_wiagets() takes the label's text and the text controlinstance.Itthen creates a horizontally oriented Soxsizer, Next you will create an instance of wx staticText using the passed-in text forits label parameter. You will also set its size to be sa pixels wide and the default heightis set with a -1. Since you want the label before the text control, you will adc the StaticText ‘widget to your BoxSizer first and then add the text control Finally, you want to add the horizontal sizer tothe top level vertical sizer. By nesting the sizes in each other, you can design complex applications. Now you will need to create the on_save() event handler so that you can save your changes: Python of on_save(seify event) self-apl.tag artist = self artist.Getvstue() sel¢.np3.tag.altun ~ self. albun.cetvalue() selt.np3.tag.titie = self tithe. Getvalue() sels.np3.tag-save() sel¥- Chose) Here you st the tags tothe contents of the text controls and then cll the eyed3 object's .save(). Finally, you cal the .close() of, ‘the dialog, The reason you cal.cose() here instead of .estroy() is that you already call .bestroy() inthe -or_eat() oF our panel subclass.Now your applications complete! Conclusion ‘You leaned alot about wxPython inthis article, You became familar with the basics of creating GU! applications using waPytho, You now know more about the following: + How to work with some of wxPython's widgets + How events workin wxeython + How absolute positioning compares with sizers + Howto create a skeleton application Finally you leamed how to create a working application, an MP3 tag editor. You can use what you learned inthis article to continue to enhance this application ar perhaps create an amazing application on your awn, The wreython GUI toolkit is robust and ull of interesting widgets that you can use to buld cross-platform applications. You are limited by only your imagination. Further Reading ¥ you would ike to learn more about wxPython, you can check out some ofthe follwing links + ‘The Official wxPython website + Zetcode's waPython cutorial + Mouse vs Python Blog For more information on what else you can do with Python, you might want to check out What Can [Do with Python? you'd ike +0 earn more about Python's super(), then Sunercharge Your Classes With Python supert) may be just right for you You can also download the cade fr the MP3 tag editor application that you created inthis article if you want to study it mre in depth Markas Completed (] 29 =) fShare @ Python Tricks @ Geta shor & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team, Email Address LSetAbout Mike Driscoll Mike has been programming n Python for over a decade and loves writing about Python! More about Mike och tutorial at Real Python is created by a team af developers so that it meets aur high quality standards, The team members who worked on this tutorial are & @ 4» Master Real-World Python Skills With Unlimited Access to Real Python - =O - Join us and get acess to thousands of tutorials, hands-on video courses, anda community of expert Pythonistas: What Do You Think? Ratethisarticle: 1 <‘What's your ft takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a ‘comment below and et us know. ‘Commenting Tips: The most useful comments are those written withthe goal of learning from or helping out other jestions in our support portal students. Get tips for asking good questions and get answers to common Looking fora real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours" Live Q&A ‘Session. Happy Pythoning! Keep Learning Related Topics: (Tenis ](=a) Related Tutorials + Python GU Programming With Tkinter * Python and ?yQt: Bullding a GU Desktap Calculator + APractcal Introduction to Web Seraping in Python * uid Scalable Flask Web Project From Scratch + PySimpleGUl:The Simple Way to Creste a GUIWith Python © Remove ads (© 2012-2024 Real Python - Newsletter - Podcast - YouTube - Twitter: Facebook - Instagram Python Tutorials - Search - Privacy Policy Energy Policy Advertise - Contac @ Happy Pythoning!
You might also like
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6389)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (634)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brené Brown
4/5 (1173)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (983)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4.5/5 (1846)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (633)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1254)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4.5/5 (4101)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (933)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (887)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (1007)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4.5/5 (1138)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (581)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (297)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (5058)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (943)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4346)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (458)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Toibin
3.5/5 (2126)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1994)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1077)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2780)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (2032)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (2876)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (141)
OpenAI Official Prompt Engineering Guide
PDF
No ratings yet
OpenAI Official Prompt Engineering Guide
17 pages
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (233)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (244)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4087)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (76)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (906)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (144)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2546)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M.L. Stedman
4.5/5 (813)
Create GUI Python Programs
PDF
No ratings yet
Create GUI Python Programs
2 pages
Support For GraphQL in generateDS
PDF
No ratings yet
Support For GraphQL in generateDS
6 pages
ERNIE
PDF
No ratings yet
ERNIE
7 pages
Learning Assistant
PDF
No ratings yet
Learning Assistant
6 pages
Paddle OCR EN
PDF
No ratings yet
Paddle OCR EN
16 pages
A Python Book Beginning Python Advanced Python and Python Exercises
PDF
No ratings yet
A Python Book Beginning Python Advanced Python and Python Exercises
261 pages
PaddlePaddle Generative Adversarial Network CN
PDF
No ratings yet
PaddlePaddle Generative Adversarial Network CN
5 pages
A Cross-Platform ChatGPT Gemini UI
PDF
No ratings yet
A Cross-Platform ChatGPT Gemini UI
15 pages
Therapist GPT
PDF
No ratings yet
Therapist GPT
2 pages
Awesome AI Agents
PDF
No ratings yet
Awesome AI Agents
35 pages
Agents
PDF
No ratings yet
Agents
4 pages
Writing & Blogging
PDF
No ratings yet
Writing & Blogging
8 pages
Learning Different Languages
PDF
No ratings yet
Learning Different Languages
9 pages
Auto GPT
PDF
No ratings yet
Auto GPT
7 pages
Kwai Agents
PDF
No ratings yet
Kwai Agents
7 pages
Fine-Tuning Llama 2 On A Custom Dataset
PDF
No ratings yet
Fine-Tuning Llama 2 On A Custom Dataset
22 pages
Document Classification With LayoutLMv3
PDF
No ratings yet
Document Classification With LayoutLMv3
25 pages
GPT-4o API Deep Dive Text Generation Vision and Function Calling
PDF
No ratings yet
GPT-4o API Deep Dive Text Generation Vision and Function Calling
21 pages
LLaVA - Large Multimodal Model
PDF
No ratings yet
LLaVA - Large Multimodal Model
15 pages
Llama 3 - Open Model That Is Truly Useful
PDF
No ratings yet
Llama 3 - Open Model That Is Truly Useful
19 pages
MemGPT - Unlimited Context (Memory) For LLMs
PDF
No ratings yet
MemGPT - Unlimited Context (Memory) For LLMs
11 pages
Flux.1-Dev - Photorealistic (And Cute) Images
PDF
100% (1)
Flux.1-Dev - Photorealistic (And Cute) Images
15 pages
Chat With Multiple PDFs Using Llama 2 and LangChain
PDF
No ratings yet
Chat With Multiple PDFs Using Llama 2 and LangChain
17 pages
Awesome Japanese NLP Resources
PDF
No ratings yet
Awesome Japanese NLP Resources
32 pages
Private Chatbot With Local LLM (Falcon 7B) and LangChain
PDF
No ratings yet
Private Chatbot With Local LLM (Falcon 7B) and LangChain
14 pages
ChatGPT-repositories ZH
PDF
No ratings yet
ChatGPT-repositories ZH
81 pages
LangChain QuickStart With Llama 2
PDF
No ratings yet
LangChain QuickStart With Llama 2
16 pages
Prompts For Large Language Models
PDF
No ratings yet
Prompts For Large Language Models
6 pages
ChatGPT-repositories JP
PDF
0% (1)
ChatGPT-repositories JP
102 pages
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4.5/5 (2369)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carre
4/5 (277)