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)
106 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
We take content rights seriously. If you suspect this is your content,
claim it here
.
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)
106 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
We take content rights seriously. If you suspect this is your content,
claim it here
.
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
OpenAI Official Prompt Engineering Guide
PDF
No ratings yet
OpenAI Official Prompt Engineering Guide
17 pages
Iti Pdfs
PDF
No ratings yet
Iti Pdfs
10 pages
De Mod 5 Deploy Workloads With Databricks Workflows
PDF
No ratings yet
De Mod 5 Deploy Workloads With Databricks Workflows
19 pages
Material For Student RWVCPC V012021A EN
PDF
No ratings yet
Material For Student RWVCPC V012021A EN
70 pages
openpyxl
PDF
No ratings yet
openpyxl
213 pages
Complete Download Fluent Python, 2nd Edition Luciano Ramalho PDF All Chapters
PDF
75% (4)
Complete Download Fluent Python, 2nd Edition Luciano Ramalho PDF All Chapters
50 pages
Cassandra Tutorial For Beginners: Learn in 3 Days: What Is Apache Cassandra?
PDF
No ratings yet
Cassandra Tutorial For Beginners: Learn in 3 Days: What Is Apache Cassandra?
4 pages
Acceleo User Guide
PDF
No ratings yet
Acceleo User Guide
56 pages
Scrapy
PDF
No ratings yet
Scrapy
306 pages
Microstrategy Tips and Techniques: Reporting Essentials Five Styles of Business Intelligence
PDF
No ratings yet
Microstrategy Tips and Techniques: Reporting Essentials Five Styles of Business Intelligence
20 pages
Git 101 For Dummies: Prologue
PDF
No ratings yet
Git 101 For Dummies: Prologue
13 pages
Ch-2 Panda: #Import The Pandas Library and Aliasing As PD
PDF
No ratings yet
Ch-2 Panda: #Import The Pandas Library and Aliasing As PD
5 pages
Duckdb Docs
PDF
No ratings yet
Duckdb Docs
721 pages
Django - Overview: MVC Pattern
PDF
No ratings yet
Django - Overview: MVC Pattern
3 pages
Dec 01 2020
PDF
No ratings yet
Dec 01 2020
298 pages
Data Engineer - Roadmap and FREE Resources - Paper 2021
PDF
No ratings yet
Data Engineer - Roadmap and FREE Resources - Paper 2021
7 pages
T-GCPBDML-B - M2 - Data Engineering For Streaming Data - ILT Slides
PDF
No ratings yet
T-GCPBDML-B - M2 - Data Engineering For Streaming Data - ILT Slides
71 pages
SAP Business Data Cloud
PDF
No ratings yet
SAP Business Data Cloud
30 pages
Pylxml
PDF
No ratings yet
Pylxml
56 pages
Stream Processing at Lyft
PDF
No ratings yet
Stream Processing at Lyft
20 pages
UBUNTU SERVER - INSTALLATION AND USER MANAGEMENT QUICK GUIDE
PDF
No ratings yet
UBUNTU SERVER - INSTALLATION AND USER MANAGEMENT QUICK GUIDE
68 pages
Change Data Capture
PDF
No ratings yet
Change Data Capture
4 pages
Neo4j-Manual-2 0 1
PDF
No ratings yet
Neo4j-Manual-2 0 1
593 pages
Creating Dataframes Reshaping Data
PDF
100% (1)
Creating Dataframes Reshaping Data
2 pages
Basic Neo4j Code Examples 2008-05-08
PDF
No ratings yet
Basic Neo4j Code Examples 2008-05-08
16 pages
C# Chart - Windows Forms
PDF
No ratings yet
C# Chart - Windows Forms
5 pages
VIP Cheatsheet: Convolutional Neural Networks: Afshine Amidi and Shervine Amidi November 26, 2018
PDF
No ratings yet
VIP Cheatsheet: Convolutional Neural Networks: Afshine Amidi and Shervine Amidi November 26, 2018
5 pages
Tableau CheatSheet Zep
PDF
No ratings yet
Tableau CheatSheet Zep
1 page
A Quick Introduction To Tensorflow: Machine Learning Spring 2019
PDF
100% (1)
A Quick Introduction To Tensorflow: Machine Learning Spring 2019
22 pages
Steps in SHA-256 Algorithm
PDF
No ratings yet
Steps in SHA-256 Algorithm
5 pages
Winforms
PDF
No ratings yet
Winforms
48 pages
D3 Tips and Tricks PDF
PDF
No ratings yet
D3 Tips and Tricks PDF
562 pages
The Official Ubuntu Book Matthew Helmke 2024 Scribd Download
PDF
100% (3)
The Official Ubuntu Book Matthew Helmke 2024 Scribd Download
62 pages
Andrew Troelsen - Pro C# 5.0 and The .NET 4.5 Framework - 2013
PDF
No ratings yet
Andrew Troelsen - Pro C# 5.0 and The .NET 4.5 Framework - 2013
1,310 pages
Big Data
PDF
No ratings yet
Big Data
18 pages
Animation: I Am Vishal Kumar Tiwari - Web Designer (Trainee) Hi
PDF
No ratings yet
Animation: I Am Vishal Kumar Tiwari - Web Designer (Trainee) Hi
12 pages
Ufl User Manual
PDF
No ratings yet
Ufl User Manual
116 pages
Graph Analytics PDF
PDF
No ratings yet
Graph Analytics PDF
13 pages
Kivymd Color
PDF
0% (1)
Kivymd Color
2 pages
HBase Succinctly PDF
PDF
No ratings yet
HBase Succinctly PDF
85 pages
Pyspark Cashing & Persisting - Complete Guide
PDF
No ratings yet
Pyspark Cashing & Persisting - Complete Guide
3 pages
Monitor Logic Apps With Azure Monitor Logs - Azure Logic Apps - Microsoft Docs
PDF
No ratings yet
Monitor Logic Apps With Azure Monitor Logs - Azure Logic Apps - Microsoft Docs
19 pages
Applied Coding Track
PDF
No ratings yet
Applied Coding Track
10 pages
SAP HANA Database SQL Command Network Protocol en
PDF
No ratings yet
SAP HANA Database SQL Command Network Protocol en
53 pages
01-Docker - 02 - Install Docker Desktop on Windows (1)
PDF
No ratings yet
01-Docker - 02 - Install Docker Desktop on Windows (1)
6 pages
IBM InfoSphere DataStage and QualityStage Version 11 Release 3 Designer Client Guide
PDF
No ratings yet
IBM InfoSphere DataStage and QualityStage Version 11 Release 3 Designer Client Guide
279 pages
Line:: Anum Kibria, Reg #550, Syn B Lab Task#1 DELIVERABLES: To Draw Basic Shapes
PDF
No ratings yet
Line:: Anum Kibria, Reg #550, Syn B Lab Task#1 DELIVERABLES: To Draw Basic Shapes
6 pages
Databricks Associate Data Engineer Notes
PDF
No ratings yet
Databricks Associate Data Engineer Notes
39 pages
Testing in Python - Unit Test & Script
PDF
No ratings yet
Testing in Python - Unit Test & Script
5 pages
Complete Download (Ebook PDF) Django For APIs: Build Web APIs With Python and Django PDF All Chapters
PDF
100% (5)
Complete Download (Ebook PDF) Django For APIs: Build Web APIs With Python and Django PDF All Chapters
51 pages
(Skiena, 2017) - Book - The Data Science Design Manual - 3
PDF
No ratings yet
(Skiena, 2017) - Book - The Data Science Design Manual - 3
1 page
Machine Learning PDF
PDF
No ratings yet
Machine Learning PDF
14 pages
Getting Started With Apache Nifi
PDF
No ratings yet
Getting Started With Apache Nifi
10 pages
Using Erwin To Model Your Data: Supplied by Computer Associates As Part of Allfusion
PDF
No ratings yet
Using Erwin To Model Your Data: Supplied by Computer Associates As Part of Allfusion
26 pages
Learning Apache Spark With Python
PDF
No ratings yet
Learning Apache Spark With Python
200 pages
Apache Spark & Scala Course Content
PDF
No ratings yet
Apache Spark & Scala Course Content
5 pages
Wxpython Application Development Cookbook - Sample Chapter
PDF
No ratings yet
Wxpython Application Development Cookbook - Sample Chapter
24 pages
Wxpython Tutorial PDF
PDF
No ratings yet
Wxpython Tutorial PDF
28 pages
Wxpython Tutorial
PDF
No ratings yet
Wxpython Tutorial
120 pages
Unit 14
PDF
No ratings yet
Unit 14
21 pages
Lec 9
PDF
No ratings yet
Lec 9
8 pages
PaddlePaddle Generative Adversarial Network CN
PDF
No ratings yet
PaddlePaddle Generative Adversarial Network CN
5 pages
Support For GraphQL in generateDS
PDF
No ratings yet
Support For GraphQL in generateDS
6 pages
Create GUI Python Programs
PDF
No ratings yet
Create GUI Python Programs
2 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
LLaVA - Large Multimodal Model
PDF
No ratings yet
LLaVA - Large Multimodal Model
15 pages
ERNIE
PDF
No ratings yet
ERNIE
7 pages
Paddle OCR EN
PDF
No ratings yet
Paddle OCR EN
16 pages
A Cross-Platform ChatGPT Gemini UI
PDF
No ratings yet
A Cross-Platform ChatGPT Gemini UI
15 pages
Learning Assistant
PDF
No ratings yet
Learning Assistant
6 pages
Learning Different Languages
PDF
No ratings yet
Learning Different Languages
9 pages
Writing & Blogging
PDF
No ratings yet
Writing & Blogging
8 pages
Therapist GPT
PDF
No ratings yet
Therapist GPT
2 pages
Awesome AI Agents
PDF
No ratings yet
Awesome AI Agents
35 pages
Kwai Agents
PDF
No ratings yet
Kwai Agents
7 pages
Document Classification With LayoutLMv3
PDF
No ratings yet
Document Classification With LayoutLMv3
25 pages
Auto GPT
PDF
No ratings yet
Auto GPT
7 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
Fine-Tuning Llama 2 On A Custom Dataset
PDF
No ratings yet
Fine-Tuning Llama 2 On A Custom Dataset
22 pages
Agents
PDF
No ratings yet
Agents
4 pages
MemGPT - Unlimited Context (Memory) For LLMs
PDF
No ratings yet
MemGPT - Unlimited Context (Memory) For LLMs
11 pages
Llama 3 - Open Model That Is Truly Useful
PDF
No ratings yet
Llama 3 - Open Model That Is Truly Useful
19 pages
Flux.1-Dev - Photorealistic (And Cute) Images
PDF
100% (1)
Flux.1-Dev - Photorealistic (And Cute) Images
15 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
ChatGPT-repositories JP
PDF
0% (1)
ChatGPT-repositories JP
102 pages
Prompts For Large Language Models
PDF
No ratings yet
Prompts For Large Language Models
6 pages
LangChain QuickStart With Llama 2
PDF
No ratings yet
LangChain QuickStart With Llama 2
16 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
ChatGPT-repositories ZH
PDF
No ratings yet
ChatGPT-repositories ZH
81 pages
Awesome Japanese NLP Resources
PDF
No ratings yet
Awesome Japanese NLP Resources
32 pages