Chuyển tới nội dung
Home » Visual Studio Python Gui | Enhance Completions With Ai

Visual Studio Python Gui | Enhance Completions With Ai

Python Desktop Application in Visual Studio 2019 | IronPython Getting Started

Next steps

To learn how to build web apps with popular Python web frameworks, see the following tutorials:

There is then much more to explore with Python in Visual Studio Code:

  • Python profile template – Create a new profile with a curated set of extensions, settings, and snippets
  • Editing code – Learn about autocomplete, IntelliSense, formatting, and refactoring for Python.
  • Linting – Enable, configure, and apply a variety of Python linters.
  • Debugging – Learn to debug Python both locally and remotely.
  • Testing – Configure test environments and discover, run, and debug tests.
  • Settings reference – Explore the full range of Python-related settings in VS Code.
  • Deploy Python to Azure App Service
  • Deploy Python to Container Apps

There are many graphical user interface (GUI) toolkits that you can use with the Python programming language. The big three are Tkinter, wxPython, and PyQt. Each of these toolkits will work with Windows, macOS, and Linux, with PyQt having the additional capability of working on mobile.

A graphical user interface is an application that has buttons, windows, and lots of other widgets that the user can use to interact with your application. A good example would be a web browser. It has buttons, tabs, and a main window where all the content loads.

In this article, you’ll learn how to build a graphical user interface with Python using the wxPython GUI toolkit.

Here are the topics covered:

  • Getting Started with wxPython
  • Definition of a GUI
  • Creating a Skeleton Application
  • Creating a Working Application

Let’s start learning!

Free Download: Get a 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.

Testing

The Python extension supports testing with Python’s built-in unittest framework and pytest.

In order to run tests, you must enable one of the supported testing frameworks in the settings of your project. Each framework has its own specific settings, such as arguments for identifying the paths and patterns for test discovery.

Once the tests have been discovered, VS Code provides a variety of commands (on the Status Bar, the Command Palette, and elsewhere) to run and debug tests. These commands also allow you to run individual test files and methods

Python Desktop Application in Visual Studio 2019 | IronPython Getting Started
Python Desktop Application in Visual Studio 2019 | IronPython Getting Started

Creating a Skeleton Application

An application skeleton in a GUI context is 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 it to your stakeholders for sign-off before spending a lot of time on the backend logic.

Let’s start by creating a

Hello World

application with wxPython:


import wx app = wx.App() frame = wx.Frame(parent=None, title='Hello World') frame.Show() app.MainLoop()

Note: Mac users may get the following message: This program needs access to the screen. Please run with a Framework build of python, and only when you are logged in on the main display of your Mac. If you see this message and you are not running in a virtualenv, then you need to run your application with pythonw instead of python. If you are running wxPython from within a virtualenv, then see the wxPython wiki for the solution.

In this example, you have two parts:

wx.App

and the

wx.Frame

. The

wx.App

is wxPython’s application object and is required for running your GUI. The

wx.App

starts something called a

.MainLoop()

. This is the event loop that you learned about in the previous section.

The other piece of the puzzle is

wx.Frame

, which will create a window for the user to interact with. In this case, you told wxPython that the frame has no parent and that its title is

Hello World

. Here is what it looks like when you run the code:

Note: The application will look different when you run it on Mac or Windows.

By default, a

wx.Frame

will include minimize, maximize, and exit buttons along the top. You won’t normally create an application in this manner though. Most wxPython code will require you to subclass the

wx.Frame

and other widgets so that you can get the full power of the toolkit.

Let’s take a moment and rewrite your code as a class:


import wx class MyFrame(wx.Frame): def __init__(self): super().__init__(parent=None, title='Hello World') self.Show() if __name__ == '__main__': app = wx.App() frame = MyFrame() app.MainLoop()

You can use this code as a template for your application. However, this application doesn’t do very much, so let’s take a moment to learn a little about some of the other widgets you could add.

Widgets

The wxPython toolkit has more than one hundred widgets to choose from. This allows you to create rich applications, but it can also be daunting trying to figure out which widget to use. This is why the wxPython Demo is helpful, as it has a search filter that you can use to help 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:


import wx class MyFrame(wx.Frame): def __init__(self): super().__init__(parent=None, title='Hello World') panel = wx.Panel(self) self.text_ctrl = wx.TextCtrl(panel, pos=(5, 5)) my_btn = wx.Button(panel, label='Press Me', pos=(5, 55)) self.Show() if __name__ == '__main__': app = wx.App() frame = MyFrame() app.MainLoop()

When you run this code, your application should look like this:

The first widget you need to add is something called

wx.Panel

. This widget is not required, but recommended. On Windows, you are actually required to use a Panel so that the background color of the frame is the right shade of gray. Tab traversal is disabled without a Panel on Windows.

When you add the panel widget to a frame and the panel is the sole child of the frame, it will automatically expand to fill the frame with itself.

The next step is to add a

wx.TextCtrl

to the panel. The first argument for almost all widgets is which parent the widget should go onto. In this case, you want the text control and the button to be on top of the panel, so it is the parent you specify.

You also need to tell wxPython where to place the widget, which you can do by passing in a position via the

pos

parameter. In wxPython, the origin location is (0,0) which is the upper left corner of the parent. So for the text control, you tell wxPython that you want to position its top left corner 5 pixels from the left (x) and 5 pixels from the top (y).

Then you add your button to the panel and give it a label. To prevent the widgets from overlapping, you need to set the y-coordinate to 55 for the button’s position.

Absolute Positioning

When you provide exact coordinates for your widget’s position, the technique that you used is called absolute positioning. Most GUI toolkits provide this capability, but it’s not actually recommended.

As your application becomes more complex, it becomes difficult to keep track of all the widget locations and if you have to move the widgets around. Resetting all those positions becomes a nightmare.

Fortunately all modern GUI toolkits provide a solution for this, which is what 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 sizers as layouts, which is what PyQt does.

Here are the primary types of sizers that you will see used most often:


  • wx.BoxSizer

  • wx.GridSizer

  • wx.FlexGridSizer

Let’s add a

wx.BoxSizer

to your example and see if we can make it work a bit more nicely:


import wx class MyFrame(wx.Frame): def __init__(self): super().__init__(parent=None, title='Hello World') panel = wx.Panel(self) my_sizer = wx.BoxSizer(wx.VERTICAL) self.text_ctrl = wx.TextCtrl(panel) my_sizer.Add(self.text_ctrl, 0, wx.ALL | wx.EXPAND, 5) my_btn = wx.Button(panel, label='Press Me') my_sizer.Add(my_btn, 0, wx.ALL | wx.CENTER, 5) panel.SetSizer(my_sizer) self.Show() if __name__ == '__main__': app = wx.App() frame = MyFrame() app.MainLoop()

Here you create an instance of a

wx.BoxSizer

and pass it

wx.VERTICAL

, which is the orientation that widgets are added to the sizer.

In this case, the widgets will be added vertically, which means they will be added one at a time from top to bottom. You may also set a BoxSizer’s orientation to

wx.HORIZONTAL

. When you do that, the widgets would be added from left to right.

To add a widget to a sizer, you will use

.Add()

. It accepts up to five arguments:


  • window

    (the widget)

  • proportion

  • flag

  • border

  • userData

The

window

argument is 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, it is zero, which tells wxPython to leave the widget at its default proportion.

The third argument is

flag

. You can actually pass in multiple flags if you wish as long as you separate them with a pipe character: . The wxPython toolkit uses to add flags using a series of bitwise ORs.

In this example, you add the text control with the

wx.ALL

and

wx.EXPAND

flags. The

wx.ALL

flag tells wxPython that you want to add a border on all sides of the widget while

wx.EXPAND

makes the widgets expand as much as they can within the sizer.

Finally, you have the

border

parameter, which tells wxPython how many pixels of border you want around the widget. The

userData

parameter is only used when you want to do something complex with your sizing of the widget and is actually quite rare to see in practice.

Adding the button to the sizer follows the exact same steps. However, to make things a bit more interesting, I went ahead and switched out the

wx.EXPAND

flag for

wx.CENTER

so that the button would be centered on-screen.

When you run this version of the code, your application should look like the following:

If you’d like to learn more about sizers, the wxPython documentation has a nice page on the topic.

Adding an Event

While your application looks more interesting visually, it still doesn’t really do anything. For example, if you press the button, nothing really happens.

Let’s give the button a job:


import wx class MyFrame(wx.Frame): def __init__(self): super().__init__(parent=None, title='Hello World') panel = wx.Panel(self) my_sizer = wx.BoxSizer(wx.VERTICAL) self.text_ctrl = wx.TextCtrl(panel) my_sizer.Add(self.text_ctrl, 0, wx.ALL | wx.EXPAND, 5) my_btn = wx.Button(panel, label='Press Me') my_btn.Bind(wx.EVT_BUTTON, self.on_press) my_sizer.Add(my_btn, 0, wx.ALL | wx.CENTER, 5) panel.SetSizer(my_sizer) self.Show() def on_press(self, event): value = self.text_ctrl.GetValue() if not value: print("You didn't enter anything!") else: print(f'You typed: "{value}"') if __name__ == '__main__': app = wx.App() frame = MyFrame() app.MainLoop()

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 f-strings. 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 it. You can accomplish this by calling the button’s

.Bind()

method.

.Bind()

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 object to the

wx.EVT_BUTTON

event and tell it to 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 up is the button press event,

wx.EVT_BUTTON

.


.on_press()

accepts a second argument that you can call

event

. This is by convention. You could call it something else if you wanted to. However, the event parameter here refers to the fact that when this method is called, its second argument should be an event object of some sort.

Within

.on_press()

, you can get the text control’s contents by calling its

GetValue()

method. You then print a string to stdout depending on what the contents of the text control is.

Now that you have the basics out of the way, let’s learn how to create an application that does something useful!

Python profile template

Profiles let you quickly switch your extensions, settings, and UI layout depending on your current project or task. To help you get started with Python development, you can use the Python profile template, which is a curated profile with useful extensions, settings, and snippets. You can use the profile template as is or use it as a starting point to customize further for you own workflows.

You select a profile template through the Profiles > Create Profile… dropdown:

Once you select a profile template, you can review the settings and extensions, and remove individual items if you don’t want to include them in your new Profile. After creating the new profile based on the template, changes made to settings, extensions, or UI are persisted in your profile.

First Python App in Visual Studio 2022 | Getting Started
First Python App in Visual Studio 2022 | Getting Started

Debugging

No more

For more specific information on debugging in Python, such as configuring your

launch.json

settings and implementing remote debugging, see Debugging. General VS Code debugging information is found in the debugging document.

Additionally, the Django and Flask tutorials provide examples of how to implement debugging in the context of web applications, including debugging Django templates.

Install Python and the Python extension

The tutorial guides you through installing Python and using the extension. You must install a Python interpreter yourself separately from the extension. For a quick install, use Python from python.org and install the extension from the VS Code Marketplace.

Note: To help get you started with Python development, you can use the Python profile template that includes useful extensions, settings, and Python code snippets.

Once you have a version of Python installed, select it using the Python: Select Interpreter command. If VS Code doesn’t automatically locate the interpreter you’re looking for, refer to Environments – Manually specify an interpreter.

You can configure the Python extension through settings. Learn more in the Python Settings reference.

Windows Subsystem for Linux: If you are on Windows, WSL is a great way to do Python development. You can run Linux distributions on Windows and Python is often already installed. When coupled with the WSL extension, you get full VS Code editing and debugging support while running in the context of WSL. To learn more, go to Developing in WSL or try the Working in WSL tutorial.

How to Install Tkinter in Visual Studio Code - (Windows 10/11)
How to Install Tkinter in Visual Studio Code – (Windows 10/11)

Run Python code

Click the Run Python File in Terminal play button in the top-right side of the editor.

The button opens a terminal panel in which your Python interpreter is automatically activated, then runs

python3 hello.py

(macOS/Linux) or

python hello.py

(Windows):

There are three other ways you can run Python code within VS Code:

  1. Right-click anywhere in the editor window and select Run > Python File in Terminal (which saves the file automatically):

  2. Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.

  3. From the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), select the Python: Start REPL command to open a REPL terminal for the currently selected Python interpreter. In the REPL, you can then enter and run lines of code one at a time.

Congrats, you just ran your first Python code in Visual Studio Code!

Conclusion

You have now learned the basics of creating a GUI application using Python and Tkinter. This tutorial covered importing Tkinter, creating a simple window, and adding a label and button. With this knowledge, you can start exploring more advanced features of Tkinter and even hire remote Python developers to help you build more complex applications.

Subreddit for posting questions and asking for general advice about your python code.

Are there any Python IDEs with a visual GUI builder?

Years ago, I used to code in Visual Basic using Visual Studio. What I love about Visual Studio is that you can use its visual GUI builder to create your application’s GUI beforehand. I’m really not a fan of coding the GUI manually.

Now I’d like to build a Windows app in Python, and I was wondering if there are any IDEs for Python that, just like Visual Studio, have a visual GUI builder.

As far as I understand, Visual Studio supports Python but it doesn’t have a visual GUI builder for Python. I know of PyCharm but I’m not sure if it has a GUI builder at all.

Does anyone know of any IDEs that might be what I am looking for? Thanks!

Develop Python applications

Python Winforms Application in Visual Studio 2019 | IronPython Getting Started
Python Winforms Application in Visual Studio 2019 | IronPython Getting Started

Conclusion

You learned a lot about wxPython in this article. You became familiar with the basics of creating GUI applications using wxPython.

You now know more about the following:

  • How to work with some of wxPython’s widgets
  • How events work in wxPython
  • How absolute positioning compares with sizers
  • How to create a skeleton application

Finally you learned how to create a working application, an MP3 tag editor. You can use what you learned in this article to continue to enhance this application or perhaps create an amazing application on your own.

The wxPython GUI toolkit is robust and full of interesting widgets that you can use to build cross-platform applications. You are limited by only your imagination.

Further Reading

If you would like to learn more about wxPython, you can check out some of the following links:

  • The Official wxPython website
  • Zetcode’s wxPython tutorial
  • Mouse Vs Python Blog

For more information on what else you can do with Python, you might want to check out What Can I Do with Python? If you’d like to learn more about Python’s

super()

, then Supercharge Your Classes With Python super() may be just right for you.

You can also download the code for the MP3 tag editor application that you created in this article if you want to study it more in depth.

Python is a versatile programming language with many libraries and frameworks, making it an ideal choice for creating Graphical User Interfaces (GUIs). This tutorial will guide you through creating a simple GUI application using Python and the popular library, Tkinter. By the end of this tutorial, you will have a basic understanding of creating GUI applications and be ready to hire remote Python developers to help you build more complex applications.

Modern Graphical User Interfaces in Python
Modern Graphical User Interfaces in Python

Autocomplete and IntelliSense

The Python extension supports code completion and IntelliSense using the currently selected interpreter. IntelliSense is a general term for a number of features, including intelligent code completion (in-context method and variable suggestions) across all your files and for built-in and third-party modules.

IntelliSense quickly shows methods, class members, and documentation as you type. You can also trigger completions at any time with ⌃Space (Windows, Linux Ctrl+Space). Hovering over identifiers will show more information about them.

Configure and run the debugger

Let’s now try debugging our Python program. Debugging support is provided by the Python Debugger extension, which is automatically installed with the Python extension. To ensure it has been installed correctly, open the Extensions view (⇧⌘X (Windows, Linux Ctrl+Shift+X)) and search for

@installed python debugger

. You should see the Python Debugger extension listed in the results.

Next, set a breakpoint on line 2 of

hello.py

by placing the cursor on the

Next, to initialize the debugger, press F5. Since this is your first time debugging this file, a configuration menu will open from the Command Palette allowing you to select the type of debug configuration you would like for the opened file.

Note: VS Code uses JSON files for all of its various configurations;


launch.json

is the standard name for a file containing debugging configurations.

Select Python File, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.

The debugger will start, and then stop at the first line of the file breakpoint. The current line is indicated with a yellow arrow in the left margin. If you examine the Local variables window at this point, you can see that the

msg

variable appears in the Local pane.

A debug toolbar appears along the top with the following commands from left to right: continue (F5), step over (F10), step into (F11), step out (⇧F11 (Windows, Linux Shift+F11)), restart (⇧⌘F5 (Windows, Linux Ctrl+Shift+F5)), and stop (⇧F5 (Windows, Linux Shift+F5)).

The Status Bar also changes color (orange in many themes) to indicate that you’re in debug mode. The Python Debug Console also appears automatically in the lower right panel to show the commands being run, along with the program output.

To continue running the program, select the continue command on the debug toolbar (F5). The debugger runs the program to the end.

Tip Debugging information can also be seen by hovering over code, such as variables. In the case of


msg

, hovering over the variable will display the string

Roll a dice!

in a box above the variable.

You can also work with variables in the Debug Console (If you don’t see it, select Debug Console in the lower right area of VS Code, or select it from the … menu.) Then try entering the following lines, one by one, at the > prompt at the bottom of the console:


msg msg.capitalize() msg.split()

Select the blue Continue button on the toolbar again (or press F5) to run the program to completion. “Roll a dice!” appears in the Python Debug Console if you switch back to it, and VS Code exits debugging mode once the program is complete.

If you restart the debugger, the debugger again stops on the first breakpoint.

To stop running a program before it’s complete, use the red square stop button on the debug toolbar (⇧F5 (Windows, Linux Shift+F5)), or use the Run > Stop debugging menu command.

For full details, see Debugging configurations, which includes notes on how to use a specific Python interpreter for debugging.

Tip: Use Logpoints instead of print statements: Developers often litter source code with

Learn Python GUI Development for Desktop – PySide6 and Qt Tutorial
Learn Python GUI Development for Desktop – PySide6 and Qt Tutorial

There are many packages in python which helps you to do that Let me explain top 3

  1. Tkinter – This comes prebuilt in your machine and it is great to start for simple UI, not recommended for large application as it lacks some functionalities
  2. PyQt – Best among all three for desktop app development comes with qt designer, in which you can convert the design in python executable, comes with many functionality
  3. Kivy – Multi-touch support, cross platform, mainly used for android development in python, not usually recommended for android apps because python lacks speed, but If you want to build personal projects to check python powers you can surely move ahead

I hope it is now clear to you 🙂

There are many packages in python which helps you to do that Let me explain top 3

  1. Tkinter – This comes prebuilt in your machine and it is great to start for simple UI, not recommended for large application as it lacks some functionalities
  2. PyQt – Best among all three for desktop app development comes with qt designer, in which you can convert the design in python executable, comes with many functionality
  3. Kivy – Multi-touch support, cross platform, mainly used for android development in python, not usually recommended for android apps because python lacks speed, but If you want to build personal projects to check python powers you can surely move ahead

I hope it is now clear to you 🙂

There are many packages in python which helps you to do that Let me explain top 3

  1. Tkinter – This comes prebuilt in your machine and it is great to start for simple UI, not recommended for large application as it lacks some functionalities
  2. PyQt – Best among all three for desktop app development comes with qt designer, in which you can convert the design in python executable, comes with many functionality
  3. Kivy – Multi-touch support, cross platform, mainly used for android development in python, not usually recommended for android apps because python lacks speed, but If you want to build personal projects to check python powers you can surely move ahead

I hope it is now clear to you 🙂

There are many packages in python which helps you to do that Let me explain top 3

  1. Tkinter – This comes prebuilt in your machine and it is great to start for simple UI, not recommended for large application as it lacks some functionalities
  2. PyQt – Best among all three for desktop app development comes with qt designer, in which you can convert the design in python executable, comes with many functionality
  3. Kivy – Multi-touch support, cross platform, mainly used for android development in python, not usually recommended for android apps because python lacks speed, but If you want to build personal projects to check python powers you can surely move ahead

I hope it is now clear to you 🙂

Building a GUI with Windows Forms in Visual Studio

You can create a module or script project.

Click File->New->Project

Select the Module or Script project type, name it and then click Ok.

After installing the Pro tools, you should now have a Form item template available. Right click on your project and select Add->New Item.

Once the New Item dialog pops up, select the PowerShell Form template, name it and click Ok.

The form designer works the same way with any language. You can select items from the Toolbox window and drag them onto your form. Properties of the controls can be set using the Properties window.

Adding controls automatically updates the Form.Designer.ps1 file. Do not edit this file by hand as the editor will simply recreate it after changes are made to the form.

To do anything interesting, you’ll need to add event handles. You can access a control’s events by selecting it in the designer and clicking the Event button in the Properties window.

Enter the name of your event handler function and click enter.

After you press enter, you will be moved into the code-behind view where you can wire up your event handler.

The event handler will automatically be wired up to your control.

Once you are ready to test out your form, you can click Start or press F5 from either the designer window or the code-behind window. PoshTools will fire off the script and you can set breakpoints and debug like any other PowerShell script.

And just like that you have a working Windows Form.

In many circumstances, you’ll want to access a control that you’ve add to the form. The $MainForm variable will have parameters for each of it’s child items. You can access those through the control’s name.

$MainForm.lblMyLabel.Value = “Some Text”

The PowerShell scripts generated by PoshProTools can be used in any PowerShell host. The designer and code-behind files can be joined into a single script. You can use the bundling functionality of PoshProTools to do this automatically.

Getting Started with Python in VS Code

In this tutorial, you will learn how to use Python 3 in Visual Studio Code to create, run, and debug a Python “Roll a dice” application, work with virtual environments, use packages, and more! By using the Python extension, you turn VS Code into a great, lightweight Python editor.

If you are new to programming, check out the Visual Studio Code for Education – Introduction to Python course. This course offers a comprehensive introduction to Python, featuring structured modules in a ready-to-code browser-based development environment.

To gain a deeper understanding of the Python language, you can explore any of the programming tutorials listed on python.org within the context of VS Code.

For a Data Science focused tutorial with Python, check out our Data Science section.

Install and use packages

Let’s build upon the previous example by using packages.

In Python, packages are how you obtain any number of useful code libraries, typically from PyPI, that provide additional functionality to your program. For this example, you use the

numpy

package to generate a random number.

Return to the Explorer view (the top-most icon on the left side, which shows files), open

hello.py

, and paste in the following source code:


import numpy as np msg = "Roll a dice" print(msg) print(np.random.randint(1,9))

Tip: If you enter the above code by hand, you may find that auto-completions change the names after the


as

keywords when you press Enter at the end of a line. To avoid this, type a space, then Enter.

Next, run the file in the debugger using the “Python: Current file” configuration as described in the last section.

You should see the message, “ModuleNotFoundError: No module named ‘numpy'”. This message indicates that the required package isn’t available in your interpreter. If you’re using an Anaconda distribution or have previously installed the

numpy

package you may not see this message.

To install the

numpy

package, stop the debugger and use the Command Palette to run Terminal: Create New Terminal (⌃⇧` (Windows, Linux Ctrl+Shift+`)). This command opens a command prompt for your selected interpreter.

To install the required packages in your virtual environment, enter the following commands as appropriate for your operating system:

  1. Install the packages


    # Don't use with Anaconda distributions because they include matplotlib already. # macOS python3 -m pip install numpy # Windows (may require elevation) py -m pip install numpy # Linux (Debian) apt-get install python3-tk python3 -m pip install numpy

  2. Now, rerun the program, with or without the debugger, to view the output!

Congrats on completing the Python tutorial! During the course of this tutorial, you learned how to create a Python project, create a virtual environment, run and debug your Python code, and install Python packages. Explore additional resources to learn how to get the most out of Python in Visual Studio Code!

Make Tkinter Look 10x Better in 5 Minutes (CustomTkinter)
Make Tkinter Look 10x Better in 5 Minutes (CustomTkinter)

Getting Started With wxPython

The wxPython GUI toolkit is a Python wrapper around a C++ library called wxWidgets. The initial release of wxPython was in 1998, so wxPython has been around quite a long time. wxPython’s primary difference from other toolkits, such as PyQt or Tkinter, is that wxPython uses the actual widgets on the native platform whenever possible. This makes wxPython applications look native to the operating system that it is running on.

PyQt and Tkinter both draw their widgets themselves, which is why they don’t always match the native widgets, although PyQt is very close.

This is not to say that wxPython does not support custom widgets. In fact, the wxPython toolkit has many custom widgets included with it, along with dozens upon dozens of core widgets. The wxPython downloads page has a section called Extra Files that is worth checking out.

Here, there is a download of the wxPython Demo package. This is a nice little 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 it in a second tab. You can even edit and re-run the code in the demo to see how your changes affect the application.

Installing wxPython

You will be using the latest wxPython for this article, which is wxPython 4, also known as the Phoenix release. The wxPython 3 and wxPython 2 versions are built only for Python 2. When Robin Dunn, the primary maintainer of wxPython, created the wxPython 4 release, he deprecated a lot of aliases and cleaned up a lot of code to make wxPython more Pythonic and easier to maintain.

You will want to consult the following links if you are migrating from an older version of wxPython to wxPython 4 (Phoenix):

  • Classic vs Phoenix
  • wxPython 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 in the legacy versions of wxPython. You can do the following to install it on your machine:


$ pip install wxpython

Note: On Mac OS X you will need a compiler installed such as XCode for the install to complete successfully. Linux may also require you to install some dependencies before the

pip

installer will work correctly.

For example, I needed to install freeglut3-dev, libgstreamer-plugins-base0.10-dev, and libwebkitgtk-3.0-dev on Xubuntu to get it to install.

Fortunately, the error messages that

pip

displays are helpful in figuring out what is missing, and you can use the prerequisites section on the wxPython Github page to help you find the information you need if you want to install wxPython on Linux.

There are some Python wheels available for the most popular Linux versions that you can find in the Extras Linux section with both GTK2 and GTK3 versions. To install one of these wheels, you would use the following command:


$ pip install -U -f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-18.04/ wxPython

Be sure you have modified the command above to match your version of Linux.

Definition of a GUI

As was mentioned in the introduction, a graphical user interface (GUI) is an interface that is drawn on the screen for the user to interact with.

User interfaces have some common components:

  • Main window
  • Menu
  • Toolbar
  • Buttons
  • Text Entry
  • Labels

All of these items are known generically as widgets. There are many other common widgets and many custom widgets that wxPython supports. A developer will take the widgets and arrange them logically on a window for the user to interact with.

Event Loops

A graphical user interface works by waiting for the user to do something. The something is called an event. Events happen when the user types something while your application is in 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 is 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 that it 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 a GUI that will take longer than a quarter second should probably be launched as a 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 let it know that the thread is finished or to give it an update.

Let’s create a skeleton application to demonstrate how events work.

Environments

The Python extension automatically detects Python interpreters that are installed in standard locations. It also detects conda environments as well as virtual environments in the workspace folder. See Configuring Python environments.

The current environment is shown on the right side of the VS Code Status Bar:

The Status Bar also indicates if no interpreter is selected:

The selected environment is used for IntelliSense, auto-completions, linting, formatting, and any other language-related feature. It is also activated when you run or debug Python in a terminal, or when you create a new terminal with the Terminal: Create New Terminal command.

To change the current interpreter, which includes switching to conda or virtual environments, select the interpreter name on the Status Bar or use the Python: Select Interpreter command.

VS Code prompts you with a list of detected environments as well as any you’ve added manually to your user settings (see Configuring Python environments).

Python Tkinter GUI Design Using ttkbootstrap - Complete Course
Python Tkinter GUI Design Using ttkbootstrap – Complete Course

Create a Python source code file

From the File Explorer toolbar, select the New File button on the

hello

folder:

Name the file

hello.py

, and VS Code will automatically open it in the editor:

By using the

.py

file extension, you tell VS Code to interpret this file as a Python program, so that it evaluates the contents with the Python extension and the selected interpreter.

Note: The File Explorer toolbar also allows you to create folders within your workspace to better organize your code. You can use the New folder button to quickly create a folder.

Now that you have a code file in your Workspace, enter the following source code in

hello.py

:


msg = "Roll a dice" print(msg)

When you start typing

IntelliSense and auto-completions work for standard Python modules as well as other packages you’ve installed into the environment of the selected Python interpreter. It also provides completions for methods available on object types. For example, because the

msg

variable contains a string, IntelliSense provides string methods when you type

msg.

:

Finally, save the file (⌘S (Windows, Linux Ctrl+S)). At this point, you’re ready to run your first Python file in VS Code.

For full details on editing, formatting, and refactoring, see Editing code. The Python extension also has full support for Linting.

Start VS Code in a workspace folder

By starting VS Code in a folder, that folder becomes your “workspace”.

Using a command prompt or terminal, create an empty folder called “hello”, navigate into it, and open VS Code (

code

) in that folder () by entering the following commands:


mkdir hello cd hello code .

Note: If you’re using an Anaconda distribution, be sure to use an Anaconda command prompt.

Alternately, you can create a folder through the operating system UI, then use VS Code’s File > Open Folder to open the project folder.

STOP Learning These Programming Languages (for Beginners)
STOP Learning These Programming Languages (for Beginners)

Configure and run the debugger

Let’s now try debugging our Python program. Debugging support is provided by the Python Debugger extension, which is automatically installed with the Python extension. To ensure it has been installed correctly, open the Extensions view (⇧⌘X (Windows, Linux Ctrl+Shift+X)) and search for

@installed python debugger

. You should see the Python Debugger extension listed in the results.

Next, set a breakpoint on line 2 of

hello.py

by placing the cursor on the

Next, to initialize the debugger, press F5. Since this is your first time debugging this file, a configuration menu will open from the Command Palette allowing you to select the type of debug configuration you would like for the opened file.

Note: VS Code uses JSON files for all of its various configurations;


launch.json

is the standard name for a file containing debugging configurations.

Select Python File, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.

The debugger will start, and then stop at the first line of the file breakpoint. The current line is indicated with a yellow arrow in the left margin. If you examine the Local variables window at this point, you can see that the

msg

variable appears in the Local pane.

A debug toolbar appears along the top with the following commands from left to right: continue (F5), step over (F10), step into (F11), step out (⇧F11 (Windows, Linux Shift+F11)), restart (⇧⌘F5 (Windows, Linux Ctrl+Shift+F5)), and stop (⇧F5 (Windows, Linux Shift+F5)).

The Status Bar also changes color (orange in many themes) to indicate that you’re in debug mode. The Python Debug Console also appears automatically in the lower right panel to show the commands being run, along with the program output.

To continue running the program, select the continue command on the debug toolbar (F5). The debugger runs the program to the end.

Tip Debugging information can also be seen by hovering over code, such as variables. In the case of


msg

, hovering over the variable will display the string

Roll a dice!

in a box above the variable.

You can also work with variables in the Debug Console (If you don’t see it, select Debug Console in the lower right area of VS Code, or select it from the … menu.) Then try entering the following lines, one by one, at the > prompt at the bottom of the console:


msg msg.capitalize() msg.split()

Select the blue Continue button on the toolbar again (or press F5) to run the program to completion. “Roll a dice!” appears in the Python Debug Console if you switch back to it, and VS Code exits debugging mode once the program is complete.

If you restart the debugger, the debugger again stops on the first breakpoint.

To stop running a program before it’s complete, use the red square stop button on the debug toolbar (⇧F5 (Windows, Linux Shift+F5)), or use the Run > Stop debugging menu command.

For full details, see Debugging configurations, which includes notes on how to use a specific Python interpreter for debugging.

Tip: Use Logpoints instead of print statements: Developers often litter source code with

Next steps

To learn how to build web apps with popular Python web frameworks, see the following tutorials:

There is then much more to explore with Python in Visual Studio Code:

  • Python profile template – Create a new profile with a curated set of extensions, settings, and snippets
  • Editing code – Learn about autocomplete, IntelliSense, formatting, and refactoring for Python.
  • Linting – Enable, configure, and apply a variety of Python linters.
  • Debugging – Learn to debug Python both locally and remotely.
  • Testing – Configure test environments and discover, run, and debug tests.
  • Settings reference – Explore the full range of Python-related settings in VS Code.
  • Deploy Python to Azure App Service
  • Deploy Python to Container Apps

Python in Visual Studio Code

Working with Python in Visual Studio Code, using the Microsoft Python extension, is simple, fun, and productive. The extension makes VS Code an excellent Python editor, and works on any operating system with a variety of Python interpreters. It leverages all of VS Code’s power to provide auto complete and IntelliSense, linting, debugging, and unit testing, along with the ability to easily switch between Python environments, including virtual and conda environments.

This article provides only an overview of the different capabilities of the Python extension for VS Code. For a walkthrough of editing, running, and debugging code, use the button below.

Best Python GUI Libraries Compared! (PyQt, Kivy, Tkinter, PySimpleGUI, WxPython & PySide)
Best Python GUI Libraries Compared! (PyQt, Kivy, Tkinter, PySimpleGUI, WxPython & PySide)

Next steps

  • Python Hello World tutorial – Get started with Python in VS Code.
  • Editing Python – Learn about auto-completion, formatting, and refactoring for Python.
  • Basic Editing – Learn about the powerful VS Code editor.
  • Code Navigation – Move quickly through your source code.
  • Django tutorial
  • Flask tutorial

Create a Python source code file

From the File Explorer toolbar, select the New File button on the

hello

folder:

Name the file

hello.py

, and VS Code will automatically open it in the editor:

By using the

.py

file extension, you tell VS Code to interpret this file as a Python program, so that it evaluates the contents with the Python extension and the selected interpreter.

Note: The File Explorer toolbar also allows you to create folders within your workspace to better organize your code. You can use the New folder button to quickly create a folder.

Now that you have a code file in your Workspace, enter the following source code in

hello.py

:


msg = "Roll a dice" print(msg)

When you start typing

IntelliSense and auto-completions work for standard Python modules as well as other packages you’ve installed into the environment of the selected Python interpreter. It also provides completions for methods available on object types. For example, because the

msg

variable contains a string, IntelliSense provides string methods when you type

msg.

:

Finally, save the file (⌘S (Windows, Linux Ctrl+S)). At this point, you’re ready to run your first Python file in VS Code.

For full details on editing, formatting, and refactoring, see Editing code. The Python extension also has full support for Linting.

Goodbye VS Code
Goodbye VS Code

Enhance completions with AI

GitHub Copilot is an AI-powered code completion tool that helps you write code faster and smarter. You can use the GitHub Copilot extension in VS Code to generate code, or to learn from the code it generates.

GitHub Copilot provides suggestions for languages beyond Python and a wide variety of frameworks, including JavaScript, TypeScript, Ruby, Go, C# and C++.

You can learn more about how to get started with Copilot in the Copilot documentation.

Jupyter notebooks

To enable Python support for Jupyter notebook files (

.ipynb

) in VS Code, you can install the Jupyter extension. The Python and Jupyter extensions work together to give you a great Notebook experience in VS Code, providing you the ability to directly view and modify code cells with IntelliSense support, as well as run and debug them.

You can also convert and open the notebook as a Python code file through the Jupyter: Export to Python Script command. The notebook’s cells are delimited in the Python file with

#%%

comments, and the Jupyter extension shows Run Cell or Run Below CodeLens. Selecting either CodeLens starts the Jupyter server and runs the cell(s) in the Python interactive window:

You can also connect to a remote Jupyter server to run your notebooks. For more information, see Jupyter support.

Microsoft FINALLY killed it
Microsoft FINALLY killed it

Run Python code

To experience Python, create a file (using the File Explorer) named

hello.py

and paste in the following code:


print("Hello World")

The Python extension then provides shortcuts to run Python code using the currently selected interpreter (Python: Select Interpreter in the Command Palette). To run the active Python file, click the Run Python File in Terminal play button in the top-right side of the editor.

You can also run individual lines or a selection of code with the Python: Run Selection/Line in Python Terminal command (Shift+Enter). If there isn’t a selection, the line with your cursor will be run in the Python Terminal. An identical Run Selection/Line in Python Terminal command is available on the context menu for a selection in the editor. The same terminal will be used every time you run a selection or a line in the terminal/REPL, until that terminal is closed. The same terminal is also used for Run Python File in Terminal. If that terminal is still running the REPL, you should exit the REPL (

exit()

) or switch to a different terminal before running a Python file.

The Python extension automatically removes indents based on the first non-empty line of the selection, shifting all other lines left as needed.

The command opens the Python Terminal if necessary; you can also open the interactive REPL environment directly using the Python: Start REPL command that activates a terminal with the currently selected interpreter and then runs the Python REPL.

For a more specific walkthrough and other ways of running code, see the run code tutorial.

Create a virtual environment

A best practice among Python developers is to use a project-specific

virtual environment

. Once you activate that environment, any packages you then install are isolated from other environments, including the global interpreter environment, reducing many complications that can arise from conflicting package versions. You can create non-global environments in VS Code using Venv or Anaconda with Python: Create Environment.

Open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), start typing the Python: Create Environment command to search, and then select the command.

The command presents a list of environment types, Venv or Conda. For this example, select Venv.

The command then presents a list of interpreters that can be used for your project. Select the interpreter you installed at the beginning of the tutorial.

After selecting the interpreter, a notification will show the progress of the environment creation and the environment folder (

/.venv

) will appear in your workspace.

Ensure your new environment is selected by using the Python: Select Interpreter command from the Command Palette.

Note: For additional information about virtual environments, or if you run into an error in the environment creation process, see Environments.

Python Project || Build A Mobile App With Python 🔥 kivy python tutorial
Python Project || Build A Mobile App With Python 🔥 kivy python tutorial

Start VS Code in a workspace folder

By starting VS Code in a folder, that folder becomes your “workspace”.

Using a command prompt or terminal, create an empty folder called “hello”, navigate into it, and open VS Code (

code

) in that folder () by entering the following commands:


mkdir hello cd hello code .

Note: If you’re using an Anaconda distribution, be sure to use an Anaconda command prompt.

Alternately, you can create a folder through the operating system UI, then use VS Code’s File > Open Folder to open the project folder.

Install a Python interpreter

Along with the Python extension, you need to install a Python interpreter. Which interpreter you use is dependent on your specific needs, but some guidance is provided below.

Windows

Install Python from python.org. Use the Download Python button that appears first on the page to download the latest version.

Note: If you don’t have admin access, an additional option for installing Python on Windows is to use the Microsoft Store. The Microsoft Store provides installs of supported Python versions.

For additional information about using Python on Windows, see Using Python on Windows at Python.org

macOS

The system install of Python on macOS is not supported. Instead, a package management system like Homebrew is recommended. To install Python using Homebrew on macOS use

brew install python3

at the Terminal prompt.

Note: On macOS, make sure the location of your VS Code installation is included in your PATH environment variable. See these setup instructions for more information.

Linux

The built-in Python 3 installation on Linux works well, but to install other Python packages you must install

pip

with get-pip.py.

Other options

  • Data Science: If your primary purpose for using Python is Data Science, then you might consider a download from Anaconda. Anaconda provides not just a Python interpreter, but many useful libraries and tools for data science.

  • Windows Subsystem for Linux: If you are working on Windows and want a Linux environment for working with Python, the Windows Subsystem for Linux (WSL) is an option for you. If you choose this option, you’ll also want to install the WSL extension. For more information about using WSL with VS Code, see VS Code Remote Development or try the Working in WSL tutorial, which will walk you through setting up WSL, installing Python, and creating a Hello World application running in WSL.

Note: To verify that you’ve installed Python successfully on your machine, run one of the following commands (depending on your operating system):

Linux/macOS: open a Terminal Window and type the following command:


python3 --version

Windows: open a command prompt and run the following command:


py -3 --version

If the installation was successful, the output window should show the version of Python that you installed. Alternatively, you can use the


py -0

command in the VS Code integrated terminal to view the versions of python installed on your machine. The default interpreter is identified by an asterisk (*).

Lập Trình Trí Tuệ Nhân Tạo Cơ Bản Tự Học Cho Người Mới Bắt Đầu | Trợ Lý Ảo Python
Lập Trình Trí Tuệ Nhân Tạo Cơ Bản Tự Học Cho Người Mới Bắt Đầu | Trợ Lý Ảo Python

Open source

Fork us on Github

Python Tools for Visual Studio is a completely free extension, developed and supported by Microsoft with contributions from the community. Visit our Github page to see or participate in PTVS development.

Getting Started with Python in VS Code

In this tutorial, you will learn how to use Python 3 in Visual Studio Code to create, run, and debug a Python “Roll a dice” application, work with virtual environments, use packages, and more! By using the Python extension, you turn VS Code into a great, lightweight Python editor.

If you are new to programming, check out the Visual Studio Code for Education – Introduction to Python course. This course offers a comprehensive introduction to Python, featuring structured modules in a ready-to-code browser-based development environment.

To gain a deeper understanding of the Python language, you can explore any of the programming tutorials listed on python.org within the context of VS Code.

For a Data Science focused tutorial with Python, check out our Data Science section.

Install and use packages

Let’s build upon the previous example by using packages.

In Python, packages are how you obtain any number of useful code libraries, typically from PyPI, that provide additional functionality to your program. For this example, you use the

numpy

package to generate a random number.

Return to the Explorer view (the top-most icon on the left side, which shows files), open

hello.py

, and paste in the following source code:


import numpy as np msg = "Roll a dice" print(msg) print(np.random.randint(1,9))

Tip: If you enter the above code by hand, you may find that auto-completions change the names after the


as

keywords when you press Enter at the end of a line. To avoid this, type a space, then Enter.

Next, run the file in the debugger using the “Python: Current file” configuration as described in the last section.

You should see the message, “ModuleNotFoundError: No module named ‘numpy'”. This message indicates that the required package isn’t available in your interpreter. If you’re using an Anaconda distribution or have previously installed the

numpy

package you may not see this message.

To install the

numpy

package, stop the debugger and use the Command Palette to run Terminal: Create New Terminal (⌃⇧` (Windows, Linux Ctrl+Shift+`)). This command opens a command prompt for your selected interpreter.

To install the required packages in your virtual environment, enter the following commands as appropriate for your operating system:

  1. Install the packages


    # Don't use with Anaconda distributions because they include matplotlib already. # macOS python3 -m pip install numpy # Windows (may require elevation) py -m pip install numpy # Linux (Debian) apt-get install python3-tk python3 -m pip install numpy

  2. Now, rerun the program, with or without the debugger, to view the output!

Congrats on completing the Python tutorial! During the course of this tutorial, you learned how to create a Python project, create a virtual environment, run and debug your Python code, and install Python packages. Explore additional resources to learn how to get the most out of Python in Visual Studio Code!

Python Tkinter GUI 🐍【𝙁𝙧𝙚𝙚】
Python Tkinter GUI 🐍【𝙁𝙧𝙚𝙚】

Version Control integration

Collaborate on code with Git

Use Git as the default source control experience in Visual Studio right out of the box. From the new Git menu, you can create or clone repositories from GitHub or Azure DevOps. Use the integrated Git tool windows to commit and push changes to your code, manage branches, sync with your remote repositories, and resolve merge conflicts.

Creating a Working Application

The first step when creating something new is to figure out what you want to create. In this case, I have taken the liberty of making that decision for you. You will learn how to create a MP3 tag editor! The next step when creating something new is to find out what packages can help you accomplish your task.

If you do a Google search for

Python mp3 tagging

, you will find you have several options:


  • mp3-tagger

  • eyeD3

  • mutagen

I tried out a couple of these and decided that eyeD3 had a nice API that you could use without getting bogged down with the MP3’s ID3 specification. You can install eyeD3 using

pip

, like this:


$ pip install eyed3

When installing this package on macOS, you may need to install

libmagic

using

brew

. Windows and Linux users shouldn’t have any issues installing eyeD3.

Designing the User Interface

When it comes to designing an interface, it’s always nice to just kind of sketch out how you think the user interface should look.

You will need to be able to do the following:

  • Open up one or more MP3 files
  • Display the current MP3 tags
  • Edit an MP3 tag

Most user interfaces use a menu or a button for opening files or folders. You can go with a File menu for this. Since you will probably want to see tags for multiple MP3 files, you will need to find a widget that can do this in a 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 a few widgets that would work for this, with the top two being the following:


  • wx.grid.Grid

  • wx.ListCtrl

You should use

wx.ListCtrl

in this case as the

Grid

widget is overkill, and frankly it is also quite a bit more complex. Finally, you need a button to use to edit a selected MP3’s tag.

Now that you know what you want, you can draw it up:

The illustration above gives us an idea of how the application should look. Now that you know what you want to do, it’s time to code!

Creating the User Interface

There are many different 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 classes? One class per file? There are many such questions, and as you get more experienced with GUI design, you’ll know how you want to answer them.

In your case, you really only need two classes:

  • A

    wx.Panel

    class
  • A

    wx.Frame

    class

You could argue for creating a controller type module as well, but for something like this, you really do not need it. A case could also be made for putting each class into its own module, but to keep it compact, you will create a single Python file for all of your code.

Let’s start with imports and the panel class:


import eyed3 import glob import wx class Mp3Panel(wx.Panel): def __init__(self, parent): super().__init__(parent) main_sizer = wx.BoxSizer(wx.VERTICAL) self.row_obj_dict = {} self.list_ctrl = wx.ListCtrl( self, size=(-1, 100), style=wx.LC_REPORT | wx.BORDER_SUNKEN ) self.list_ctrl.InsertColumn(0, 'Artist', width=140) self.list_ctrl.InsertColumn(1, 'Album', width=140) self.list_ctrl.InsertColumn(2, 'Title', width=200) main_sizer.Add(self.list_ctrl, 0, wx.ALL | wx.EXPAND, 5) edit_button = wx.Button(self, label='Edit') edit_button.Bind(wx.EVT_BUTTON, self.on_edit) main_sizer.Add(edit_button, 0, wx.ALL | wx.CENTER, 5) self.SetSizer(main_sizer) def on_edit(self, event): print('in on_edit') def update_mp3_listing(self, folder_path): print(folder_path)

Here, you import the

eyed3

package, Python’s

glob

package, and the

wx

package for your user interface. Next, you subclass

wx.Panel

and create your user interface. You need a dictionary for storing data about your MP3s, which you can name

row_obj_dict

.

Then you create a

wx.ListCtrl

and set it to report mode (

wx.LC_REPORT

) with a sunken border (

wx.BORDER_SUNKEN

). The list control can take on a few other forms depending on the style flag that you pass in, but the report flag is the most popular.

To make the

ListCtrl

have the correct headers, you will need to call

.InsertColumn()

for each column header. You then supply the index of the column, its label, and how wide in pixels the column should be.

The last step is to add your

Edit

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 code for the frame:


class Mp3Frame(wx.Frame): def __init__(self): super().__init__(parent=None, title='Mp3 Tag Editor') self.panel = Mp3Panel(self) self.Show() if __name__ == '__main__': app = wx.App(False) frame = Mp3Frame() app.MainLoop()

This class is much simpler than the first one in that all you need to do is set the title of the frame and instantiate the panel class,

Mp3Panel

. When you are all done, your user interface should look like this:

The user interface looks almost right, but you don’t have a File menu. This makes it impossible to add MP3s to the application and edit their tags!

Let’s fix that now.

Make a Functioning Application

The first step in making your application work is to update the application so that it has a File menu because then you can add MP3 files to your creation. Menus are almost always added to the

wx.Frame

class, so that is the class you need to modify.

Note: Some applications have moved away from having menus in their applications. One of the first to do so was Microsoft Office when they added the Ribbon Bar. The wxPython toolkit has a custom widget that you can use to create ribbons in

wx.lib.agw.ribbon

.

The other type of application 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 a menu bar to our application:


class Mp3Frame(wx.Frame): def __init__(self): wx.Frame.__init__(self, parent=None, title='Mp3 Tag Editor') self.panel = Mp3Panel(self) self.create_menu() self.Show() def create_menu(self): menu_bar = wx.MenuBar() file_menu = wx.Menu() open_folder_menu_item = file_menu.Append( wx.ID_ANY, 'Open Folder', 'Open a folder with MP3s' ) menu_bar.Append(file_menu, '&File') self.Bind( event=wx.EVT_MENU, handler=self.on_open_folder, source=open_folder_menu_item, ) self.SetMenuBar(menu_bar) def on_open_folder(self, event): title = "Choose a directory:" dlg = wx.DirDialog(self, title, style=wx.DD_DEFAULT_STYLE) if dlg.ShowModal() == wx.ID_OK: self.panel.update_mp3_listing(dlg.GetPath()) dlg.Destroy()

Here, you add a call to

.create_menu()

within the class’s constructor. Then in

.create_menu()

itself, you will create a

wx.MenuBar

instance and a

wx.Menu

instance.

To add a menu item to a menu, you call the menu instance’s

.Append()

and pass it the following:

  • A unique identifier
  • The label for the new menu item
  • A help string

Next, you need to add the menu to the menubar, so you will need to call the menubar’s

.Append()

. It takes the menu instance and the label for menu. This label is a bit odd in that you called it

&File

instead of

File

. The ampersand tells wxPython to create a keyboard shortcut of Alt+F to open the

File

menu using just your keyboard.

Note: If you would like to add keyboard shortcuts to your application, then you will want to use an instance of

wx.AcceleratorTable

to create them. You can read more about Accerator Tables in the wxPython documentation.

To create an event binding, you will need to call

self.Bind()

, which binds the frame to

wx.EVT_MENU

. When you use

self.Bind()

for a menu event, you need to not only tell wxPython which

handler

to use, but also which

source

to bind the handler to.

Finally, you must call the frame’s

.SetMenuBar()

and pass it the menubar instance for it to be shown to the user.

Now that you have the menu added to your frame, let’s go over the menu item’s event handler, which is reproduced again below:


def on_open_folder(self, event): title = "Choose a directory:" dlg = wx.DirDialog(self, title, style=wx.DD_DEFAULT_STYLE) if dlg.ShowModal() == wx.ID_OK: self.panel.update_mp3_listing(dlg.GetPath()) dlg.Destroy()

Since you want the user to choose a folder that contains MP3s, you will want to use wxPython’s

wx.DirDialog

. The

wx.DirDialog

allows the user to only open directories.

You can set the dialog’s title and various style flags. To show the dialog, you will need to call

.ShowModal()

. 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 is shown.

If the user presses the dialog’s OK button, you can get the user’s path choice via the dialog’s

.GetPath()

. You will want to pass that path to your panel class, which you can do here by calling the panel’s

.update_mp3_listing()

.

Finally you need to close the dialog. To close a dialog, the recommended method is to call its

.Destroy()

.

Dialogs do have a

.Close()

method, but that basically just hides the dialog, and it will not destroy itself when you close your application, which can lead to weird issues such as your application now shutting down properly. It’s simpler to call

.Destroy()

on the dialog to prevent this issue.

Now let’s update your

Mp3Panel

class. You can start by updating

.update_mp3_listing()

:


def update_mp3_listing(self, folder_path): self.current_folder_path = folder_path self.list_ctrl.ClearAll() self.list_ctrl.InsertColumn(0, 'Artist', width=140) self.list_ctrl.InsertColumn(1, 'Album', width=140) self.list_ctrl.InsertColumn(2, 'Title', width=200) self.list_ctrl.InsertColumn(3, 'Year', width=200) mp3s = glob.glob(folder_path + '/*.mp3') mp3_objects = [] index = 0 for mp3 in mp3s: mp3_object = eyed3.load(mp3) self.list_ctrl.InsertItem(index, mp3_object.tag.artist) self.list_ctrl.SetItem(index, 1, mp3_object.tag.album) self.list_ctrl.SetItem(index, 2, mp3_object.tag.title) mp3_objects.append(mp3_object) self.row_obj_dict[index] = mp3_object index += 1

Here you set the current directory to the specified folder and then you clear the list control. This keeps the list control fresh and only showing the MP3s that you are currently working on. That also means that you need to re-insert all the columns again.

Next, you’ll want to take the folder that was passed in and use Python’s

glob

module to search for MP3 files.

Then you can loop over the MP3s and turn them into

eyed3

objects. You can do this by calling the

.load()

of

eyed3

. Assuming that the MP3s have the appropriate tags already, you can then add the artist, album, and title of the MP3 to the list control.

Interestingly, the method of adding a new row to a list control object is by calling

.InsertItem()

for the first column and

SetItem()

for all the subsequent columns.

The last step is to save off your MP3 object to your Python dictionary,

row_obj_dict

.

Now you need to update the

.on_edit()

event handler so that you can edit an MP3’s tags:


def on_edit(self, event): selection = self.list_ctrl.GetFocusedItem() if selection >= 0: mp3 = self.row_obj_dict[selection] dlg = EditDialog(mp3) dlg.ShowModal() self.update_mp3_listing(self.current_folder_path) dlg.Destroy()

The first thing you need to do is get the user’s selection by calling the list control’s

.GetFocusedItem()

.

If the user has not selected anything in the list control, it will return

-1

. Assuming that the user did select something, you will want to extract the MP3 object from your dictionary and open a MP3 tag editor dialog. This will be a custom dialog that you will use to edit the artist, album, and title tags of the MP3 file.

As usual, show the dialog modally. When the dialog closes, the last two lines in

.on_edit()

will execute. These two lines will update the list control so it displays the current MP3 tag information that the user just edited and destroy the dialog.

Creating an Editing Dialog

The final piece of the puzzle is creating an MP3 tag editing dialog. For brevity, we will skip sketching out this interface as it is a series of rows that contains labels and text controls. The text controls should have the existing tag information pre-populated within them. You can create a label for the text controls by creating instances of

wx.StaticText

.

When you need to create a custom dialog, the

wx.Dialog

class is your friend. You can use that to design the editor:


class EditDialog(wx.Dialog): def __init__(self, mp3): title = f'Editing "{mp3.tag.title}"' super().__init__(parent=None, title=title) self.mp3 = mp3 self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.artist = wx.TextCtrl( self, value=self.mp3.tag.artist) self.add_widgets('Artist', self.artist) self.album = wx.TextCtrl( self, value=self.mp3.tag.album) self.add_widgets('Album', self.album) self.title = wx.TextCtrl( self, value=self.mp3.tag.title) self.add_widgets('Title', self.title) btn_sizer = wx.BoxSizer() save_btn = wx.Button(self, label='Save') save_btn.Bind(wx.EVT_BUTTON, self.on_save) btn_sizer.Add(save_btn, 0, wx.ALL, 5) btn_sizer.Add(wx.Button( self, id=wx.ID_CANCEL), 0, wx.ALL, 5) self.main_sizer.Add(btn_sizer, 0, wx.CENTER) self.SetSizer(self.main_sizer)

Here you want to start off by sub-classing

wx.Dialog

and giving it a custom title based on the title of the 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

.add_widgets()

for adding the

wx.StaticText

widgets as rows with the text control instances. The only other widget here is the Save button.

Let’s write the

add_widgets

method next:


def add_widgets(self, label_text, text_ctrl): row_sizer = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=label_text, size=(50, -1)) row_sizer.Add(label, 0, wx.ALL, 5) row_sizer.Add(text_ctrl, 1, wx.ALL | wx.EXPAND, 5) self.main_sizer.Add(row_sizer, 0, wx.EXPAND)


add_widgets()

takes the label’s text and the text control instance. It then creates a horizontally oriented

BoxSizer

.

Next you will create an instance of

wx.StaticText

using the passed-in text for its label parameter. You will also set its size to be

50

pixels wide and the default height is set with a

-1

. Since you want the label before the text control, you will add the StaticText widget to your BoxSizer first and then add the text control .

Finally, you want to add the horizontal sizer to the top level vertical sizer. By nesting the sizers 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:


def on_save(self, event): self.mp3.tag.artist = self.artist.GetValue() self.mp3.tag.album = self.album.GetValue() self.mp3.tag.title = self.title.GetValue() self.mp3.tag.save() self.Close()

Here you set the tags to the contents of the text controls and then call the

eyed3

object’s

.save()

. Finally, you call the

.Close()

of the dialog. The reason you call .

Close()

here instead of

.Destroy()

is that you already call

.Destroy()

in the

.on_edit()

of your panel subclass.

Now your application is complete!

Python Projects ~ Build Mobile App With Python ~ App Development From Scratch
Python Projects ~ Build Mobile App With Python ~ App Development From Scratch

Create a virtual environment

A best practice among Python developers is to use a project-specific

virtual environment

. Once you activate that environment, any packages you then install are isolated from other environments, including the global interpreter environment, reducing many complications that can arise from conflicting package versions. You can create non-global environments in VS Code using Venv or Anaconda with Python: Create Environment.

Open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), start typing the Python: Create Environment command to search, and then select the command.

The command presents a list of environment types, Venv or Conda. For this example, select Venv.

The command then presents a list of interpreters that can be used for your project. Select the interpreter you installed at the beginning of the tutorial.

After selecting the interpreter, a notification will show the progress of the environment creation and the environment folder (

/.venv

) will appear in your workspace.

Ensure your new environment is selected by using the Python: Select Interpreter command from the Command Palette.

Note: For additional information about virtual environments, or if you run into an error in the environment creation process, see Environments.

Install a Python interpreter

Along with the Python extension, you need to install a Python interpreter. Which interpreter you use is dependent on your specific needs, but some guidance is provided below.

Windows

Install Python from python.org. Use the Download Python button that appears first on the page to download the latest version.

Note: If you don’t have admin access, an additional option for installing Python on Windows is to use the Microsoft Store. The Microsoft Store provides installs of supported Python versions.

For additional information about using Python on Windows, see Using Python on Windows at Python.org

macOS

The system install of Python on macOS is not supported. Instead, a package management system like Homebrew is recommended. To install Python using Homebrew on macOS use

brew install python3

at the Terminal prompt.

Note: On macOS, make sure the location of your VS Code installation is included in your PATH environment variable. See these setup instructions for more information.

Linux

The built-in Python 3 installation on Linux works well, but to install other Python packages you must install

pip

with get-pip.py.

Other options

  • Data Science: If your primary purpose for using Python is Data Science, then you might consider a download from Anaconda. Anaconda provides not just a Python interpreter, but many useful libraries and tools for data science.

  • Windows Subsystem for Linux: If you are working on Windows and want a Linux environment for working with Python, the Windows Subsystem for Linux (WSL) is an option for you. If you choose this option, you’ll also want to install the WSL extension. For more information about using WSL with VS Code, see VS Code Remote Development or try the Working in WSL tutorial, which will walk you through setting up WSL, installing Python, and creating a Hello World application running in WSL.

Note: To verify that you’ve installed Python successfully on your machine, run one of the following commands (depending on your operating system):

Linux/macOS: open a Terminal Window and type the following command:


python3 --version

Windows: open a command prompt and run the following command:


py -3 --version

If the installation was successful, the output window should show the version of Python that you installed. Alternatively, you can use the


py -0

command in the VS Code integrated terminal to view the versions of python installed on your machine. The default interpreter is identified by an asterisk (*).

Create Beautiful Python GUI in 10 Minutes 🐍 | Tkinter Designer Tutorial
Create Beautiful Python GUI in 10 Minutes 🐍 | Tkinter Designer Tutorial

Run Python code

Click the Run Python File in Terminal play button in the top-right side of the editor.

The button opens a terminal panel in which your Python interpreter is automatically activated, then runs

python3 hello.py

(macOS/Linux) or

python hello.py

(Windows):

There are three other ways you can run Python code within VS Code:

  1. Right-click anywhere in the editor window and select Run > Python File in Terminal (which saves the file automatically):

  2. Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.

  3. From the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), select the Python: Start REPL command to open a REPL terminal for the currently selected Python interpreter. In the REPL, you can then enter and run lines of code one at a time.

Congrats, you just ran your first Python code in Visual Studio Code!

Getting Started with Tkinter

Tkinter is a widely-used Python library for creating GUI applications. It is a built-in library in Python, so you don’t need to install it separately. To get started, let’s create a simple window using Tkinter.

Importing Tkinter

Open your IDE and create a new Python file. Name it ‘gui_app.py’. Next, import the Tkinter library by adding the following line to your file:


import tkinter as tk

Creating a Basic Window

Now that you have imported Tkinter, you can create a simple window using the following code:


import tkinter as tk def main(): # Create a Tkinter window window = tk.Tk() # Set the window title window.title('My GUI App') # Set the window size window.geometry('300x200') # Start the main event loop window.mainloop() if __name__ == '__main__': main()

Save and run the file (gui_app.py) in your terminal with the following command:


python gui_app.py

A window titled ‘My GUI App’ with the size of 300×200 pixels should appear on your screen. Congratulations! You have just created your first simple GUI application using Python and Tkinter.

Adding a Label and Button

Next, add a label and a button to our window. To do this, modify the ‘main()’ function in your ‘gui_app.py’ file as follows:


def main(): # Create a Tkinter window window = tk.Tk() # Set the window title window.title('My GUI App') # Set the window size window.geometry('300x200') # Create a label label = tk.Label(window, text='Hello, Tkinter!') label.pack() # Create a button button = tk.Button(window, text='Click me!', command=on_button_click) button.pack() # Start the main event loop window.mainloop() def on_button_click(): print('Button clicked!')

Save and run the file again. You should now see a label displaying ‘Hello, Tkinter!’ and a button with the text ‘Click me!’. When you click the button, the text ‘Button clicked!’ will be printed in the terminal.

How to Setup Python on Microsoft Visual Studio 2022 | Amit Thinks
How to Setup Python on Microsoft Visual Studio 2022 | Amit Thinks

Other popular Python extensions

The Microsoft Python extension provides all of the features described previously in this article. Additional Python language support can be added to VS Code by installing other popular Python extensions.

  1. Open the Extensions view (⇧⌘X (Windows, Linux Ctrl+Shift+X)).
  2. Filter the extension list by typing ‘python’.

The extensions shown above are dynamically queried. Click on an extension tile above to read the description and reviews to decide which extension is best for you. See more in the Marketplace.

Keywords searched by users: visual studio python gui

C# To Python(Tkinter) Coverter (Visual Studio) Using Bunifupy Library -  Youtube
C# To Python(Tkinter) Coverter (Visual Studio) Using Bunifupy Library – Youtube
Python Support In Visual Studio On Windows | Microsoft Learn
Python Support In Visual Studio On Windows | Microsoft Learn
Python In Visual Studio Tutorial Step 1, Create A Project | Microsoft Learn
Python In Visual Studio Tutorial Step 1, Create A Project | Microsoft Learn
Python Development In Visual Studio Code – Real Python
Python Development In Visual Studio Code – Real Python
Visual Studio Python Ide - Python Development Tools For Windows
Visual Studio Python Ide – Python Development Tools For Windows
Visual Studio Code User Interface - Course Vs Code & Python - Youtube
Visual Studio Code User Interface – Course Vs Code & Python – Youtube
First Python App In Visual Studio 2022 | Getting Started - Youtube
First Python App In Visual Studio 2022 | Getting Started – Youtube
Python Development In Visual Studio Code – Real Python
Python Development In Visual Studio Code – Real Python
Setting Up Vscode For Python: A Complete Guide | Datacamp
Setting Up Vscode For Python: A Complete Guide | Datacamp
Python Calculator Tutorial In Visual Studio 2015 - Youtube
Python Calculator Tutorial In Visual Studio 2015 – Youtube
How To Create Your First Python Gui With Vs Code | Python Gui Tutorial  Using Tkinter - Youtube
How To Create Your First Python Gui With Vs Code | Python Gui Tutorial Using Tkinter – Youtube
Python | Simple Gui Calculator Using Tkinter - Geeksforgeeks
Python | Simple Gui Calculator Using Tkinter – Geeksforgeeks
How To Install Tkinter In Visual Studio Code - (Windows 10/11) - Youtube
How To Install Tkinter In Visual Studio Code – (Windows 10/11) – Youtube
Introduction To Visual Studio - Geeksforgeeks
Introduction To Visual Studio – Geeksforgeeks
A Lap Around Python In Visual Studio 2017 - Visual Studio Blog
A Lap Around Python In Visual Studio 2017 – Visual Studio Blog
Python Gui Programming With Tkinter – Real Python
Python Gui Programming With Tkinter – Real Python
Learn About Powerful Python Decorators In A Delphi Windows Gui App
Learn About Powerful Python Decorators In A Delphi Windows Gui App

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *