Пример Hello Word с использованием Windows Forms
Во-первых, ссылки будут добавлены в сборки CLR, которые будут использоваться.
import clr
clr.AddReference('System.Windows.Forms')
Затем будут импортированы имена, которые мы будем использовать.
from System.Windows.Forms import Application, Form
Класс будет создан для формы Hello World, используя Form
качестве своего подкласса.
class HelloWorldForm(System.Windows.Forms.Form):
def __init__(self):
self.Text = 'Hello World'
self.Name = 'Hello World'
Текстовый атрибут формы устанавливает текст заголовка.
Чтобы запустить приложение, мы создаем экземпляр HelloWorldForm
.
form = HelloWorldForm()
Application.Run(form)
Класс Application
предоставляет статические методы, такие как запуск и остановка приложения. Статический метод Run
запускает форму в текущем потоке.
This blog article shows you how to create a simple Winform using Python.
Creating a Windows Form application using Python typically involves using a library that provides bindings to the Windows GUI. One of the popular libraries for this purpose is pywin32, but a more modern and versatile approach is to use PyQt or PySide, which are Python bindings for the Qt application framework.
Here’s an example using PyQt5 to create a simple Windows Form application:
1. Install PyQt5: First, you need to install the PyQt5 package. You can install it using pip:
pip install PyQt5
2. Create a simple Windows Form: The following code demonstrates how to create a basic Windows Form with a button and a label.
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout
class MyForm(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# Create a button
self.button = QPushButton(‘Click Me’, self)
self.button.clicked.connect(self.on_click)
# Create a label
self.label = QLabel(‘Hello, PyQt5!’, self)
# Create a layout and add widgets
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
# Set the layout on the application’s window
self.setLayout(layout)
# Set window title and size
self.setWindowTitle(‘My First PyQt5 App’)
self.setGeometry(100, 100, 300, 200)
def on_click(self):
self.label.setText(‘Button Clicked!’)
if __name__ == ‘__main__’:
app = QApplication(sys.argv)
form = MyForm()
form.show()
sys.exit(app.exec_())
When you run the code then you will see the Winform as follows.
Also: Predict Value with Python Machine Learning
Below are some takeaway:
- Imports:
- QApplication: Manages the GUI application’s control flow and main settings.
- QWidget: The base class for all UI objects in PyQt.
- QPushButton: Provides a command button.
- QLabel: Displays text or an image.
- QVBoxLayout: Provides a vertical box layout.
- MyForm Class: Inherits from QWidget and sets up the user interface in initUI method.
- self.button: A button widget.
- self.label: A label widget.
- QVBoxLayout: Manages the layout of child widgets in a vertical box.
- on_click: A method connected to the button’s click signal to change the label’s text.
- Main Application:
- QApplication instance is created.
- An instance of MyForm is created and displayed.
- The application’s event loop is started with app.exec_().
This example creates a simple form with a button and a label. When the button is clicked, the label text changes. This serves as a basic introduction to creating Windows Forms with PyQt5 in Python.
Source code download: https://github.com/chanmmn/python/tree/main/2024/PythonWinform?WT.mc_id=DP-MVP-36769
Reference: https://www.geeksforgeeks.org/python-introduction-to-pyqt5/?WT.mc_id=DP-MVP-36769
About chanmingman
Since March 2011 Microsoft Live Spaces migrated to WordPress (http://www.pcworld.com/article/206455/Microsoft_Live_Spaces_Moves_to_WordPress_An_FAQ.html) till now, I have is over 1 million viewers. This blog is about more than 50% telling you how to resolve error messages, especial for Microsoft products. The blog also has a lot of guidance teaching you how to get stated certain Microsoft technologies. The blog also uses as a help to keep my memory. The blog is never meant to give people consulting services or silver bullet solutions. It is a contribution to the community. Thanks for your support over the years.
Ming Man is Microsoft MVP since year 2006. He is a software development manager for a multinational company. With 25 years of experience in the IT field, he has developed system using Clipper, COBOL, VB5, VB6, VB.NET, Java and C #. He has been using Visual Studio (.NET) since the Beta back in year 2000. He and the team have developed many projects using .NET platform such as SCM, and HR based applications. He is familiar with the N-Tier design of business application and is also an expert with database experience in MS SQL, Oracle and AS 400.
Python is a versatile programming language that is widely used for various applications, including web development, data analysis, and desktop applications. One of the popular ways to create desktop applications in Python is by using Windows Forms. This tutorial will guide you through the process of generating Windows Forms in Python, focusing on the use of the tkinter
library, which is included with most Python installations.
What is Tkinter?
tkinter
is the standard GUI (Graphical User Interface) toolkit for Python. It provides a simple way to create windows, dialogs, buttons, and other GUI elements. Tkinter is built on the Tk GUI toolkit, which is cross-platform and works on Windows, macOS, and Linux.
Setting Up Your Environment
Before you start coding, ensure that you have Python installed on your system. You can download the latest version from the official Python website. Tkinter comes pre-installed with Python, so you don’t need to install it separately.
Creating Your First Windows Form
Let’s create a simple Windows Form application that includes a label, an entry field, and a button. When the button is clicked, it will display the text entered in the entry field.
Step 1: Import Tkinter
import tkinter as tk
Step 2: Create the Main Application Window
root = tk.Tk()
root.title("My First Windows Form")
root.geometry("300x200") # Width x Height
Step 3: Add Widgets
Now, let’s add a label, an entry field, and a button to the window.
# Create a label
label = tk.Label(root, text="Enter your name:")
label.pack(pady=10) # Add some vertical padding
# Create an entry field
entry = tk.Entry(root)
entry.pack(pady=10)
# Function to display the entered name
def display_name():
name = entry.get()
greeting_label = tk.Label(root, text=f"Hello, {name}!")
greeting_label.pack(pady=10)
# Create a button
button = tk.Button(root, text="Submit", command=display_name)
button.pack(pady=10)
Step 4: Run the Application
root.mainloop()
Putting it all together, your complete code should look like this:
import tkinter as tk
root = tk.Tk()
root.title("My First Windows Form")
root.geometry("300x200")
label = tk.Label(root, text="Enter your name:")
label.pack(pady=10)
entry = tk.Entry(root)
entry.pack(pady=10)
def display_name():
name = entry.get()
greeting_label = tk.Label(root, text=f"Hello, {name}!")
greeting_label.pack(pady=10)
button = tk.Button(root, text="Submit", command=display_name)
button.pack(pady=10)
root.mainloop()
Understanding the Code
In this code:
tk.Tk()
initializes the main application window.Label
,Entry
, andButton
are widgets that represent different GUI elements.pack()
is a geometry manager that organizes widgets in blocks before placing them in the parent widget.- The
display_name
function retrieves the text from the entry field and displays a greeting when the button is clicked.
Conclusion
Creating Windows Forms in Python using Tkinter is straightforward and allows for rapid development of desktop applications. This tutorial covered the basics of setting up a simple form with user input. As you become more familiar with Tkinter, you can explore additional widgets, layout managers, and event handling to create more complex applications.
Summary
In this tutorial, we explored how to generate Windows Forms in Python using the Tkinter library. By following the steps outlined, you can create simple GUI applications that enhance user interaction. For those looking to deploy their applications effectively, consider utilizing a reliable VPS solution for hosting your Python applications. With USA VPS Hosting, you can ensure that your applications run smoothly and efficiently.
Whether you need a fancy GUI for your Python app, you have an existing Python desktop app which needs some additional functionality or you are mainly interested in a different theme that will freshen up your app, we are here for you. All this is possible with the help of Telerik UI For WinForms Controls.
You read that right! IronPython and the latest Visual Studio 2019 made all this possible! They enable Python desktop applications to work together with WinForms controls. And more importantly, work together with the Telerik UI For WinForms suite and all the goodies that come out of the bag.
Iron Python
IronPython is a powerful open-source variation of Python. It is an adaptation of the Python programming language that runs on top of Microsoft’s .NET framework. IronPython can use the .NET Framework and Python libraries, and other .NET languages can use Python code just as easily.
After you install the latest version of IronPython, you can open Visual Studio 2019 which comes with a built-in template project for “IronPython Windows Forms Application” and create your first app.
How to Integrate Telerik RadGridView in Your Application with a Modern Fluent Theme Applied
Now let’s make a huge step onto using Telerik controls. First, you need to install the Telerik UI for WinForms UI component suite—you can download it from here. Then add the required Telerik assemblies into your project folder for using the RadGridView, FluentTheme and RadChartView (spoiler alert—we will need it for later) controls for WinForms.
To reference the binaries in the app, import the clr library and then use the addReference methods. Here you can see how to add references
and usings
that we are going to need for our sample app.
import
clr
import
random
clr.AddReference(
'System.Drawing'
)
clr.AddReference(
'System.Windows.Forms'
)
clr.AddReference(
'Telerik.WinControls'
)
clr.AddReference(
'Telerik.WinControls.UI'
)
clr.AddReference(
'Telerik.WinControls.ChartView'
)
clr.AddReference(
'Telerik.WinControls.Themes.Fluent'
)
clr.AddReference(
'TelerikCommon'
)
clr.AddReference(
'Telerik.WinControls.GridView'
)
from
System.Drawing
import
*
from
System.Windows.Forms
import
*
from
Telerik.WinControls
import
*
from
Telerik.WinControls.UI
import
*
from
Telerik.Charting
import
*
from
Telerik.WinControls.Themes
import
*
Now let’s take a look how we can add a radGridView control, containing a bunch of different columns to our form.
#Define RadGridView
self
.radGrid
=
RadGridView()
self
.radGrid.BestFitColumns()
self
.radGrid.ForeColor
=
Color.Black
self
.radGrid.Dock
=
DockStyle.Fill
#Define Columns
self
.decimalColumn
=
GridViewDecimalColumn()
self
.textBoxColumn
=
GridViewTextBoxColumn()
self
.colorColumn
=
GridViewColorColumn()
self
.checkBoxColumn
=
GridViewCheckBoxColumn()
self
.ratingColumn
=
GridViewRatingColumn()
self
.decimalColumn.HeaderText
=
"DecimalColumn"
self
.textBoxColumn.HeaderText
=
"Text"
self
.colorColumn.HeaderText
=
"ColorColumn"
self
.checkBoxColumn.HeaderText
=
"CheckBoxColumn"
self
.ratingColumn.HeaderText
=
"RatingColumn"
self
.radGrid.Columns.Add(
self
.decimalColumn)
self
.radGrid.Columns.Add(
self
.textBoxColumn)
self
.radGrid.Columns.Add(
self
.colorColumn)
self
.radGrid.Columns.Add(
self
.checkBoxColumn)
self
.radGrid.Columns.Add(
self
.ratingColumn)
self
.Controls.Add(
self
.radGrid)
#Populate Rows
for
index
in
range(
10
):
self
.radGrid.Rows.Add(index,
"Sample Text "
+
str(index), Color.FromArgb(random.randint(
1
,
255
), random.randint(
1
,
255
), random.randint(
1
,
255
)), CheckState.Checked, random.randint(
1
,
100
))
The result of this exercise is a radGridView which has the following columns: GridViewDecimalColumn, GridViewTextBoxColumn, GridViewColorColumn, GridViewCheckBoxColumn, GridViewRatingColumn.
If you would like to apply a theme to your controls, as seen in the picture, it can be done as simple as that.
fluent
=
FluentTheme()
self
.ThemeName
=
fluent.ThemeName
self
.radGrid.ThemeName
=
fluent.ThemeName
Subscribing to Events and Implementing Your Business Logic
In case you wonder how subscribing to events works it is easier than you might think. Here is a sample of creating a RadButton control and subscribing to its Click
event.
#Define RadButton1
self
.myButton1
=
RadButton()
self
.myButton1.Text
=
"RadButton1"
self
.myButton1.Click
+
=
self
.OnButton1Click
self
.Controls.Add(
self
.myButton1)
Then as you know you will have to define your OnButtonClick logic.
def
OnButton1Click(
self
, sender, args):
#TODO OnClick logic
So far so good. Now let’s look at a more complex event-related example using the radGridView from our previous example. We will implement some logic in the CellFormatting event in order to fill cells from GridViewRatingColumn with different colors. The value inside the Rating cells can be between 0 and 100. If the value is < 50 we will fill those cells in Red color, otherwise we will use Aqua color. We can achieve this result with the following code.
def
OnRadGridCellFormatting(
self
, sender, args):
if
args
is
not
None
:
if
args.Column.HeaderText
=
=
"RatingColumn"
:
if
args.CellElement.RowInfo.Cells[
4
].Value
is
not
None
:
if
args.CellElement.Value >
50
:
args.CellElement.DrawFill
=
True
args.CellElement.ForeColor
=
Color.Blue
args.CellElement.NumberOfColors
=
1
args.CellElement.BackColor
=
Color.Aqua
else
:
args.CellElement.DrawFill
=
True
args.CellElement.ForeColor
=
Color.Yellow
args.CellElement.NumberOfColors
=
1
args.CellElement.BackColor
=
Color.Red
else
:
args.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local)
args.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local)
args.CellElement.ResetValue(LightVisualElement.NumberOfColorsProperty, ValueResetFlags.Local)
args.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local)
The end result of our CellFormatting effort looks like that.
A Little Bonus Setup Example with RadChartView
Using Telerik controls is as easy as you saw in the radGridView example. Let’s look at another example of setting up radChartView control with BarSeries.
#Define RadChartView
self
.chartView
=
RadChartView()
self
.chartView.Size
=
Size(
290
,
160
)
self
.chartView.Dock
=
DockStyle.Fill
#Define BarSeries and CategoricDataPoints
self
.barSeries
=
BarSeries(
"Performance"
,
"RepresentativeName"
)
self
.barSeries.Name
=
"Q1"
self
.categoricDataPoint1
=
CategoricalDataPoint(
177
,
"Harley"
)
self
.categoricDataPoint2
=
CategoricalDataPoint(
128
,
"White"
)
self
.categoricDataPoint3
=
CategoricalDataPoint(
143
,
"Smith"
)
self
.categoricDataPoint4
=
CategoricalDataPoint(
111
,
"Jones"
)
self
.barSeries.DataPoints.Add(
self
.categoricDataPoint1)
self
.barSeries.DataPoints.Add(
self
.categoricDataPoint2)
self
.barSeries.DataPoints.Add(
self
.categoricDataPoint3)
self
.barSeries.DataPoints.Add(
self
.categoricDataPoint4)
self
.chartView.Series.Add(
self
.barSeries)
self
.Controls.Add(
self
.chartView)
The result is as you might expect for a standard Telerik UI for WinForms application.
Summary
This was a short intro to combining Python desktop GUI and the Telerik UI for WinForms suite. Please don’t hesitate to share your experience with integrating Telerik UI for WinForms in your Python projects.
Feel more than welcome to drop us a line in the comments section bellow on how it went with our components or submit your feedback directly to our Feedback Portal. You can download the latest version of Telerik UI for WinForms from your account today, or if you’re new to the suite, start a free 30 day trial today:
Start My Trial
Winforms with Python
|
|
Building a WinForms applicationWith python.net configured, we can now build a basic Winforms application running from CPython. First let’s use Visual Studio to build a basic form and compile it into an clr assembly. For below example, I created a form called SimpleForm in SimpleForm namespace and packaged it inside SimpleForm.dll. The form has text field called textBox and a button called btn_sayit. The following python code can then be used launch the form and handle click event on btn_sayit to print contents of textBox to the console. import clr from System.Reflection import Assembly from System.Windows.Forms import Application Assembly.LoadFile(r‘c:\work\simple_form\SimpleForm.DLL’) import SimpleForm form = SimpleForm.SimpleForm() def event_handler(sender, args): print(«Got Text: %s» % form.textBox.Text) form.btn_sayit.Click += event_handler Application.Run(form) To simplify the python interface, I’ve set Modifier as public on textBox and btn_sayit widgets, this is not strictly necessary as you can also get access to them using form.Controls collection, but it makes for simpler and cleaner interface |
|
|
|
Handling real-time updatesMost modern UIs also update based on some external events, not just user actions. To support that, we need to extend our model and include an event mechanism that will flow events from python to the WinForms layer. In the previous section, when we invoked Application.Run() on the view, we’ve effectively handed control over the the windows message loop(http://en.wikipedia.org/wiki/Message_loop_in_Microsoft_Windows) and any further updates must be performed from a python thread that should have been started before the Application.Run() has been called. Furthermore, WinForms are not thread-safe, therefore one must use Invoke or BeginInvoke to update the UI. import clr from System.Reflection import Assembly from System.Windows.Forms import Application from System.Windows.Forms import MethodInvoker Assembly.LoadFile(r‘c:\work\simple_form\SimpleForm.DLL’) import SimpleForm import threading import random import time class View(SimpleForm.SimpleForm): @property def text(self): return self.textBox.Text @text.setter def text(self, value): def updater(): self.textBox.Text = str(value) self.BeginInvoke(MethodInvoker(updater)) def bind_handler(self, handler): self.btn_sayit.Click += handler class Presenter: def __init__(self, view, model, event_generator): self.view = view self.model = model self.event_generator = event_generator self.bind_events() def bind_events(self): self.view.bind_handler(self.sayit_handler) self.event_generator.bind_handler(self.update_text) def update_text(self, new_text): self.view.text = new_text def sayit_handler(self, sender, args): self.model.perform_sayit(self.view.text) class Model: def perform_sayit(self, text): print(«Got Text: %s» % text) class EventGenerator(threading.Thread): _handler = None def bind_handler(self, handler): self._handler = handler def run(self): while True: if self._handler: self._handler( random.random() ) time.sleep( 1 ) generator = EventGenerator() generator.setDaemon(True) generator.start() p = Presenter(View(), Model(), generator) Application.Run(p.view) |