0% found this document useful (0 votes)
7 views33 pages

Chapter III

Chapter III focuses on the development of graphical user interfaces (GUIs) for civil engineering software, emphasizing the importance of user-friendly designs that facilitate interaction with complex calculations and models. It provides an overview of the Visual Studio IDE, detailing its features and capabilities for GUI development using frameworks like WinForms and Tkinter. The chapter also discusses event handling, the components of Windows Forms applications, and the tools available in the Visual Studio GUI builder to streamline the development process.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views33 pages

Chapter III

Chapter III focuses on the development of graphical user interfaces (GUIs) for civil engineering software, emphasizing the importance of user-friendly designs that facilitate interaction with complex calculations and models. It provides an overview of the Visual Studio IDE, detailing its features and capabilities for GUI development using frameworks like WinForms and Tkinter. The chapter also discusses event handling, the components of Windows Forms applications, and the tools available in the Visual Studio GUI builder to streamline the development process.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter III: Graphical user interface development

Chapter III: Graphical user


interface development
III.1. Introduc on
III.2. Overview of the Visual Studio IDE
III.3. WinForms 3 weeks
III.4. Tkinter
III.5. Events handling

Note: This lesson has been enhanced in grammar, style, and structure using an AI tool to improve clarity and
readability.

64 BAKHTI RACHID
Chapter III: Graphical user interface development

III.1. Introduc on:


Developing so ware for civil engineering increasingly relies on crea ng efficient and user-friendly
graphical user interfaces (GUIs). A GUI allows engineers to interact with complex calcula ons,
models, and simula ons through bu ons, menus, forms, and visual components instead of typing
commands into a console. This makes engineering so ware more intui ve, faster to use, and
accessible to a wider range of users.

Modern civil-engineering tools—such as COVADIS, PISTE, ROBBAT, CiviLab, and SAP—are built
around well-designed interfaces that guide the user through each task. Behind these interfaces is
source code, wri en in programming languages like Visual Basic, Delphi, C/C++, or [Link], which
defines the structure and behavior of every window, control, and interac on.

GUI development typically begins by defining what the user needs to see and how they will
interact with the program. Frameworks such as WinForms (for C#/.NET) and Tkinter (for Python)
provide pre-built components—windows, labels, text boxes, bu ons, menus—that can be
arranged to create applica ons tailored to engineering workflows.

A central concept in GUI programming is event handling. GUIs operate based on events: when a
user clicks a bu on, moves the mouse, selects an item, or enters data, an event is generated. The
program must detect these events and execute the appropriate instruc ons. The quality of a GUI
depends heavily on how clearly and efficiently these events are managed.

Tes ng and refinement are essen al steps—developers must ensure that each interac on works
as expected, responds correctly to user input, and produces accurate results.

Building GUI-based applica ons for civil engineering requires understanding not only
programming fundamentals but also the principles of interface design and event-driven logic.
Mastering tools like WinForms and Tkinter enables engineers to create powerful, prac cal
so ware that improves produc vity and enhances the user experience.

65 BAKHTI RACHID
Chapter III: Graphical user interface development

III.2. Overview of the Visual Studio IDE


Visual Studio is one of the most advanced and widely used Integrated Development Environments
(IDEs) for building applica ons on Windows and across mul ple pla orms. Its history reflects the
evolu on of Microso ’s development ecosystem.

The first version, Visual Studio 97, was released in 1997 and included tools for Visual Basic, Visual
C++, and other languages. Over the following years, Visual Studio grew into a unified environment
capable of suppor ng a large variety of programming languages and technologies.

A major milestone came with Visual Studio .NET (2002), which introduced the .NET Framework,
fundamentally changing how Windows applica ons were designed, compiled, and executed. From
that point onward, Visual Studio became the primary development environment for .NET
applica ons.

Subsequent releases—Visual Studio 2005, 2008, 2010, 2012, 2015, 2017, 2019, 2022—con nued
to expand support for web, cloud, mobile, and cross-pla orm development, while greatly
improving produc vity tools such as IntelliSense, refactoring, and debugging capabili es. Today,
Visual Studio remains a reference IDE in the industry, known for its powerful features and rich
ecosystem. The most recent release is Visual Studio 2026.

What Is an Integrated Development Environment (IDE)?

An Integrated Development Environment (IDE) is a so ware applica on that brings together all
the tools needed to design, write, test, and maintain programs. Its purpose is to simplify and
streamline the development workflow by combining mul ple tools into a single interface. Key
components of a modern IDE include:

 Code Editor: Provides syntax highlighting, auto-completion (IntelliSense), code


formatting, and navigation.
 Compiler/Interpreter: Translates high-level code into machine-readable instructions or
executes it directly.

66 BAKHTI RACHID
Chapter III: Graphical user interface development

 Debugger: Allows developers to run code step by step, inspect variables, set
breakpoints, and diagnose errors.
 Build Tools: Automate compilation, linking, packaging, and generation of executable
files.
 Project & Solution Management: Organizes files, dependencies, and settings in a
structured way.
 Version Control Integration: Enables direct interaction with Git or other version control
systems.
 GUI Designers & Specialized Tools: Visual tools for creating graphical interfaces,
managing databases, designing classes, etc.
 Error Checking & Code Analysis: Real-time detection of syntax errors, code suggestions,
and best-practice guidance.
 Documentation Tools: Automated generation of comments, XML documentation, and
API references.
 Extensions & Plugins: Additional components that can enhance productivity, add
languages, or integrate external tools.

An IDE’s main goal is to help developers write better software, faster, and with fewer errors.

Ge ng Started with Visual Studio 2022 (or Later)

Visual Studio provides a wide range of project templates to help developers start applications
quickly. For GUI development and .NET-based applications, the most relevant project types
include:

 Windows Forms Applications


 Class Libraries
 Windows Forms Control Libraries
 Windows Forms Class Libraries
 WPF Applications

67 BAKHTI RACHID
Chapter III: Graphical user interface development

 WPF Class Libraries


 WPF Custom Control Libraries
 WPF User Control Libraries
 And many more…

These templates cover different levels of project complexity and allow developers to choose the
structure that best fits their needs—whether they are building desktop applications, component
libraries, or reusable UI controls.

68 BAKHTI RACHID
Chapter III: Graphical user interface development

Mul ple programming languages are available in VS2022 such as Visual basic, C#, C++, F#, JavaScript, and
Python

Addi onally, users have the flexibility to choose the target opera ng system for their developed project.
This selec on can encompass a range of op ons, including Mul pla orm, Windows, Linux, Android, iOS,
macOS, and more.

69 BAKHTI RACHID
Chapter III: Graphical user interface development

III.3. Windows Forms Applica ons


Windows Forms (WinForms) is a mature and widely-used framework for building na ve Windows
desktop applica ons. It's a fundamental part of the Microso .NET ecosystem, offering developers
a powerful toolset for crea ng useful and responsive so ware. WinForms applica ons are
characterized by their intui ve graphical user interfaces, making it easy for users to interact with
the so ware. The framework provides a comprehensive library of controls, including bu ons,
textboxes, grids, and more, that can be easily customized to meet specific design and func onality
requirements.

One of WinForms' strengths is its rapid applica on development capabili es. Developers can
leverage Visual Studio, Microso 's integrated development environment (IDE), to quickly design,
code, and debug applica ons. This results in shorter development cycles and faster me-to-
market.

WinForms also supports event-driven programming, allowing developers to respond to user


ac ons, such as bu on clicks or mouse events, with ease. This event-driven model simplifies
building interac ve and responsive applica ons. Furthermore, WinForms seamlessly integrates
with other .NET technologies, enabling developers to harness the full power of the .NET
Framework. It supports data binding, making it straigh orward to connect user interfaces to
databases and display real- me data.

In summary, Windows Forms remains a robust choice for crea ng na ve Windows applica ons,
whether it's for business so ware, u li es, games, or any other type of desktop applica on. Its
combina on of a rich control library, rapid development capabili es, and deep integra on with
the .NET ecosystem makes it a go-to solu on for developers aiming to deliver user-friendly and
feature-rich Windows applica ons.

III.3.1. Create WinForms App:


To create a new WinForms App project, just follow these straigh orward steps:

 Begin by choosing "Windows Forms App" and proceed by clicking the "Next" bu on.

70 BAKHTI RACHID
Chapter III: Graphical user interface development

 Input essen al project details, including the project name, project path, and solu on name.
A erward, click the "Next" bu on.
 Now, you have the op on to select the preferred framework. Once you've made your choice,
click the "Create" bu on to ini ate the project setup.

These steps provide a seamless way to ini ate a new WinForms App project in a few simple clicks,
ensuring a smooth and efficient start to your development process.

71 BAKHTI RACHID
Chapter III: Graphical user interface development

III.3.2. The Graphical User Interface (GUI) builder of WinForms

72 BAKHTI RACHID
Chapter III: Graphical user interface development

The graphical user interface (GUI) builder for Windows Forms App projects in Visual Studio is a
powerful tool that streamlines the applica on development process. It comprises four essen al
mini-windows, each serving a dis nct purpose:

 Toolbox Window: This window is a treasure trove of various tools and controls that
developers can easily access. It simplifies the process of adding bu ons, textboxes, grids,
and other UI elements to the form.
 Forms Window: In this window, developers can flex their crea ve muscles and design the
visual layout of the Windows App. It provides an intui ve drag-and-drop interface for
placing controls and arranging them as desired.
 Solu on Explorer Window: Naviga ng through the components of your project is a
breeze with this window. It offers a structured view of the project's files, making it easy
to find and manage resources.
 Property Window: Tailoring the appearance and behavior of UI elements is made
effortless with the Property window. Developers can select a tool or control and view
and edit its proper es, such as size, color, text, and more.

Together, these four mini-windows empower developers to efficiently create and fine-tune the
user interface of their Windows Forms App projects, promo ng a seamless and produc ve
development experience.

III.3.3. Components of a Windows Forms Applica on


In a Windows Forms applica on developed using [Link], the key components include:

 Forms: Forms are the main windows or screens in your applica on. They serve as
containers for other controls and provide the user interface. Forms can be designed
visually using the Windows Forms Designer in Visual Studio or created programma cally.
 Controls: Controls are UI (User Interface) elements placed on forms to enable user
interac on. Examples include bu ons, textboxes, labels, checkboxes, radio bu ons, and
more. These controls are added to forms to create the desired user interface.

73 BAKHTI RACHID
Chapter III: Graphical user interface development

 Classes: Classes in [Link] are used to define custom data types and contain methods
and proper es that define the behavior of objects. In a Windows Forms applica on, you
can create custom classes to encapsulate specific func onality, such as data handling or
business logic.
 Modules: Modules are a way to organize code in [Link]. They are similar to classes but
don't require an instance to be created. Modules o en contain shared procedures and
func ons that can be accessed globally across the applica on.
 Event Handlers: Event handlers are methods or func ons that respond to specific events
raised by controls. For example, you can write code in an event handler to handle bu on
clicks or text changes. Event handlers are essen al for crea ng interac ve applica ons.
 Resources: Resources are used to store applica on assets such as images, icons, and
strings. They can be embedded in your applica on or stored externally as files. Resources
are typically managed using resource files (.resx) in Visual Studio.
 Se ngs: Se ngs allow you to persist user-specific configura on data such as user
preferences or applica on se ngs. These se ngs can be accessed and modified during
run me.
 Data Access: In many Windows Forms applica ons, you'll work with databases or other
data sources. You may use classes or libraries to connect to and manipulate data, such as
[Link] for database access.
 References: References are links to external libraries or assemblies that your applica on
depends on. These references can include .NET Framework libraries, third-party libraries,
or custom libraries you've created.
 Deployment Configura on: Deployment configura on refers to the process of se ng up
and configuring your so ware applica on for distribu on and installa on on end-users'
systems. It involves making decisions and adjustments to ensure that your applica on
can be deployed and run smoothly on various target environments

74 BAKHTI RACHID
Chapter III: Graphical user interface development

These components work together to create a fully func onal Windows Forms applica on in
[Link], allowing you to design a rich user interface and implement the necessary func onality
to meet your applica on's requirements.

III.3.4. Toolbox Components


In the WinForms GUI builder, the toolbox in the WinForms GUI builder contains a variety of
controls and components that you can drag and drop onto your form. These tools or controls can
be used to create the user interface for your Windows-based applica on. Here are some of the
common controls and components available in the WinForms toolbox:
1. Bu on: A control that allows users to trigger an ac on by clicking on it.
2. Label: Used to display text on a form to provide informa on or instruc ons.
3. TextBox: An input control for users to enter text.
4. ComboBox: A drop-down list of items, from which users can select one.
5. ListBox: A list of items that users can select one or more items from.
6. RadioBu on: Used for selec ng a single op on from a group of mutually exclusive op ons.
7. CheckBox: Used for toggling a binary choice on or off.
8. PictureBox: A control for displaying images.
9. Panel: A container for grouping other controls. It helps in organizing the layout of your form.
10. GroupBox: A container with a border and op onal cap on for grouping related controls.
11. TabControl: Allows you to create tabbed interfaces, with each tab containing different content.
12. TreeView: Used for displaying hierarchical data in a tree structure.
13. ListView: A list control that can display items in various views, such as a list or icons.
14. MenuStrip: A container for crea ng menu bars in your applica on.
15. ContextMenuStrip: A container for crea ng context menus, which appear when you right-click
on a control.
16. ToolStrip: A container for crea ng toolbars with bu ons and dropdowns.
17. StatusStrip: A container for crea ng status bars that display informa on about the
applica on's state.

75 BAKHTI RACHID
Chapter III: Graphical user interface development

18. ProgressBar: A control that shows the progress of an opera on.


19. TrackBar: A slider control for selec ng a value within a range.
20. DateTimePicker: Allows users to select dates and mes.
21. NumericUpDown: A control for selec ng numeric values by incremen ng or decremen ng.
22. Timer: Allows you to create mer-based events in your applica on.
23. WebBrowser: Embeds a web browser within your applica on.
24. RichTextBox: An advanced text box control with forma ng op ons.
25. ToolTip: A control for providing tool ps when users hover over other controls.
26. DataGrid: is a versa le control for displaying and edi ng tabular data with customizable
columns and features.
27. Chart control in WinForms is a powerful graphical component used to display numerical data
in visual form. It allows developers to create professional charts such as line charts, bar charts, pie
charts, area charts, and many others
These are just some of the common controls and components available in the WinForms toolbox.
Depending on your development environment, you may also have access to custom or third-party
controls to extend the func onality of your applica on. You can drag these controls onto your
form, set their proper es, and write code to handle events and interac ons as needed for your
applica on's user interface.

III.3.5. MenuStrip and ContextMenuStrip


Designing a menu in a WinForms applica on is crucial for providing an intui ve and user-friendly
interface. Two main types of menus are available in Winfoms, namely:
a- ContextMenuStrip : In WinForms (Windows Forms), a ContextMenuStrip is a graphical
user interface (GUI) control that provides context-sensi ve menus or pop-up menus in
Windows-based applica ons. It's designed to be displayed when a user right-clicks on a
control, such as a form, a bu on, or any other UI element, to present a list of ac ons or
op ons relevant to the context of the control

76 BAKHTI RACHID
Chapter III: Graphical user interface development

b- MenuStrip : In WinForms, a MenuStrip is a graphical user interface (GUI) control used to


create tradi onal, top-level menus in Windows-based applica ons. These menus are
typically displayed at the top of a form and provide a structured way for users to access
various applica on func ons and features. The MenuStrip control is a fundamental
component for crea ng menu systems in WinForms applica ons

Here are some key principles to consider when crea ng a menu:


1. Clear Hierarchy: Start with a clear hierarchy, placing the most important func ons at the top-
level menu. Group related items together to make naviga on easier.
2. Use Icons: Icons can provide visual cues and enhance the menu's aesthe cs. Use descrip ve
icons to represent menu items when applicable.
3. Keyboard Shortcuts: Assign keyboard shortcuts (e.g., Ctrl+C for Copy) for frequently used
ac ons. Make sure to display these shortcuts alongside menu items.
4. Search Func onality: Implement a search feature within your menu if you have an extensive
list of op ons to make it easier for users to find what they need.
5. Submenus: For complex applica ons, use submenus to organize related func ons.
6. Labels: Use clear and concise labels for menu items. Avoid abbrevia ons that might not be
easily understood.
7. Tool Tips: Include tool ps to provide addi onal informa on when users hover over a menu
item, aiding comprehension.
8. Separators: Employ separators between menu groups to visually organize and dis nguish
different sets of ac ons.
9. Disable Unavailable Op ons: Gray out or disable menu items that are not applicable in the
current context to prevent user frustra on.
10. Dynamic Menus: Create dynamic menus that adapt to the user's role or the applica on's state.
Show or hide menu items as needed.
11. Recent Items: Include a "Recent" or "History" menu to help users access recently used files or
ac ons quickly.

77 BAKHTI RACHID
Chapter III: Graphical user interface development

Remember, a well-designed menu system enhances user produc vity and sa sfac on, making it
a fundamental aspect of any WinForms applica on.

Applica on 01:
Create a basic menu using a `MenuStrip` control in a WinForms applica on. In this example, we'll
create a File menu with "New File", “Open”, and “Save" op ons and a separator line

1. Drag and drop a `MenuStrip` control from the Toolbox onto your form. It will be placed at the
top of your form by default.
2. Click on the `MenuStrip` control to select it.
3. In the Proper es window, find the `Items` property and click the ellipsis bu on (…) to open the
Menu Designer.
4. In the Menu Designer, add a new menu item under the `MenuStrip` by right-clicking the
`MenuStrip` and choosing "Add" Set the text property to "File."
5. Click the "File" menu to select it, find the `DropDownItems` property and click the ellipsis bu on
(…) to open the Menu Designer. In the Menu Designer, add two submenu items: "New", "Open."
And “Save”. Also add a separator
6. Set the text proper es for "New", "Open." And Save as follows:
 "New" for the first submenu item.
 "Open" for the second submenu item.
 "Save" for the third submenu item.
7. In the Menu Designer, click "OK" to close the Menu Designer.
That's a basic example of crea ng a menu in WinForms. You can expand and customize your menu
with addi onal menu items and func onality as needed for your applica on.

78 BAKHTI RACHID
Chapter III: Graphical user interface development

Crea ng a `ContextMenuStrip` in a WinForms applica on is essen al when you want to provide


context-sensi ve menus that appear when a user right-clicks on a control or an area within your
form. Here's a step-by-step guide on how to create and u lize a `ContextMenuStrip` in
WinForms:

79 BAKHTI RACHID
Chapter III: Graphical user interface development

Add the ContextMenuStrip Control:

1. In the toolbox, find the "ContextMenuStrip" control. It's usually located under the "Menus &
Toolbars" sec on.

2. Drag and drop the `ContextMenuStrip` control onto your form. It won't be visible at run me
but will appear in the component tray at the bo om of the designer.

3. Click on the `ContextMenuStrip` control in the component tray.

4. In the Proper es window, click the ellipsis (...) bu on next to the "Items" property to open the
Menu Designer.

5. In the Menu Designer, you can add menu items by right-clicking the `MenuItems` and
choosing "Add"

6. Customize the proper es of the menu items, such as se ng their text, shortcuts, icons, and
event handlers.

7. To make the `ContextMenuStrip` appear when a user right-clicks on a control, select the
control. In the Proper es window, find the "ContextMenuStrip" property and set it to the
`ContextMenuStrip` you've created. This associates the menu with the control.

III.3.6. TextBox
The `TextBox` control is a fundamental component in Windows Forms (WinForms) applica ons,
enabling users to input and edit textual informa on. This control is widely used for various data
entry and text display purposes. In this sec on, we'll explore the `TextBox` control and how to add
it to a WinForms form.
The `TextBox` control offers the following key features:
1. Text Input: Users can type or paste text into the `TextBox`, making it suitable for various data
input tasks, such as user registra on forms, search boxes, and text edi ng.
2. Mul line Text: The `TextBox` can be configured as a single-line input or a mul line text area,
allowing users to enter and edit longer text content.

80 BAKHTI RACHID
Chapter III: Graphical user interface development

3. Read-Only and Disabled: The `TextBox` control can be set to read-only mode or disabled to
prevent user input while s ll displaying informa on.
Adding a TextBox to a WinForms Form:

To add a `TextBox` control to a WinForms form, follow these steps:


1. Locate the Toolbox: In the toolbox, find the "TextBox" control. It's represented by an icon that
looks like a text input field.
2. Drag and Drop: Click on the "TextBox" icon in the toolbox and drag it onto your form. Release
the mouse bu on to place the `TextBox` on the form.
3. Resize and Posi on: Resize and reposi on the `TextBox` as needed by clicking and dragging its
edges or corners. You can also use the Proper es window to set the size and loca on precisely.
4. Customize Proper es: Use the Proper es window to set various proper es of the `TextBox`,
such as `Mul line`, `ReadOnly`, and `Text`. You can also set valida on proper es and define event
handlers for user interac ons.
The `TextBox` control is a mul purpose tool for text input and display in WinForms applica ons.
By adding and customizing this control, you can create user-friendly forms and enable users to
interact with your applica on effec vely.
Applica on 02:
Create the same menu of applica on 01 as a `ContextMenuStrip` control and associate it with
the Form.
' Set default text
[Link] = "Enter your name here"
' Read the text entered by the user
Dim userName As String = [Link]
[Link]("You entered: " & userName)
' Make a TextBox mul line and adjust size
[Link] line = True
[Link] = New Size(200, 100)
' Mask input for password
[Link] = "*"c
' Limit the number of characters
[Link] = 20

81 BAKHTI RACHID
Chapter III: Graphical user interface development

III.3.7. Label Control


The `Label` control is a fundamental element in Windows Forms (WinForms) applica ons,
primarily used for displaying sta c text or providing descrip ons for other controls. Labels play a
crucial role in enhancing the user interface and guiding users through an applica on. The `Label`
control offers the following key features:
1. Text Display: Labels are designed to display text or cap ons, making them ideal for providing
informa on or instruc ons within a form.
2. Sta c Content: Labels are non-editable and non-interac ve by default, ensuring that the
displayed text remains sta c and cannot be modified by the user.
3. Enhanced User Experience: Properly labeled controls help users understand the purpose and
func on of adjacent input fields, bu ons, or other controls, improving the overall user experience.
4. Styling and Customiza on: Developers can customize the appearance of labels by adjus ng
proper es like font, color, alignment, and size to match the applica on's design and layout.
5. Localiza on: Labels support localiza on efforts by allowing you to display text in different
languages or adapt content to specific regions and cultures.

To add a `Label` control to a WinForms form, follow these steps:


1. Locate the Toolbox: In the toolbox, find the "Label" control. It's represented by an icon that
looks like a simple text box.
2. Drag and Drop: Click on the "Label" icon in the toolbox and drag it onto your form. Release the
mouse bu on to place the label on the form.
3. Edit the Text: With the label selected, you can immediately edit the text displayed on the label.
Simply click on the label's text and modify it to suit your needs.
4. Resize and Posi on: Resize and reposi on the label as needed by clicking and dragging its edges
or corners. You can also use the Proper es window to set the size and loca on precisely.
5. Customize Proper es: Use the Proper es window to customize the label's appearance, such as
font, color, alignment, and size. You can also set proper es like `AutoSize` to adjust the label's size
automa cally based on its content.

82 BAKHTI RACHID
Chapter III: Graphical user interface development

The `Label` control is a fundamental tool for enhancing the clarity and usability of WinForms
applica ons. By adding and customizing labels strategically, you can create intui ve and
informa ve user interfaces that guide users through your applica on's features and func ons.
' Change the text of the label
[Link] = "Hello, this is a Label control!"
' Update the label based on user input (for example, a TextBox)
[Link] = "You entered: " & [Link]
' Change font and color programma cally
[Link] = New Font("Arial", 12, [Link])
[Link] = [Link]
' Display mul line text
[Link] = False
[Link] = New Size(200, 60)
[Link] = "Line 1" & vbCrLf & "Line 2" & vbCrLf & "Line 3"

III.3.8. DataGridView
A DataGridView is a fundamental component in Windows Forms (WinForms) applica ons,
designed to efficiently display and manipulate tabular data. It provides a user-friendly interface
for presen ng data in a grid format, making it a vital tool for crea ng database-driven applica ons,
reports, and data management tools.

To add a DataGridView to a WinForms applica on, follow these basic steps:


1. Drag and Drop: From the Toolbox, drag and drop a DataGridView control onto your form. You
can find it under the "Data" sec on.
2. Data Binding: To populate the DataGridView with data, you can set its `DataSource` property
to a data source like a dataset, data table, or a binding source. This can be done programma cally
or using the Proper es window.
3. Column Configura on: Customize the DataGridView by specifying columns, their data sources,
and proper es. You can do this both visually in the designer and programma cally in code.
4. Forma ng: You can style the DataGridView with forma ng op ons like colors, fonts, and cell
borders to match your applica on's visual theme.

83 BAKHTI RACHID
Chapter III: Graphical user interface development

5. Expor ng: Implement export func onality to enable users to save data from the DataGridView
to various file formats like CSV or Excel (the implementa on can be done programma cally in
code).
' Create a DataTable to store data
Dim dt As New DataTable()
' Add columns
[Link]("ID", GetType(Integer))
[Link]("Name", GetType(String))
[Link]("Value", GetType(Double))
' Add sample rows
[Link](1, "Item A", 12.5)
[Link](2, "Item B", 18.9)
[Link](3, "Item C", 7.3)
' Bind the DataTable to the DataGridView
[Link] = dt
' ----------------------------------------
' Read a cell value
' Example: read the "Value" of the first row
Dim firstValue As Double
firstValue = [Link]([Link](0).Cells(2).Value)
[Link]("The value of the first row is: " & firstValue)
' ----------------------------------------
' Set or modify a cell value
' Example: change the "Name" of the second row
[Link](1).Cells(1).Value = "Updated Item B"

III.3.9. Chart
A Chart is an essential component in Windows Forms (WinForms) applications used to visually
represent numerical data in graphical form. It provides a clear and interactive way to display
trends, comparisons, and relationships through various chart types such as line, bar, pie, area, or
scatter plots. This makes the Chart control particularly valuable in applications that involve
scientific data, engineering results, statistics, or any scenario where visual analysis is required.

To add a Chart control to a WinForms application, follow these basic steps:

84 BAKHTI RACHID
Chapter III: Graphical user interface development

1. Drag and Drop: From the Toolbox, drag and drop a Chart control onto your form. It is
located under the "Data" section. Visual Studio will automatically add a default ChartArea
and a default Series.
2. Series Configuration: A Chart is composed of one or more series, each representing a set
of data points. Configure the chart type (e.g., Line, Bar, Pie) and add or remove series in
the designer or in code.
3. Data Binding: Populate the Chart by adding data points or binding it to a data source such
as an array, list, or DataTable. Data can be added manually or dynamically at runtime.
4. Customization: Customize the chart’s appearance by modifying colors, titles, legends,
axes, or gridlines. You can also style markers, labels, and backgrounds to fit your
application’s design.
5. Interactivity: The Chart control supports events such as clicking, hovering, or zooming,
allowing users to interact with the displayed data.

' Clear existing series


[Link]()

' Add a new series


[Link]("MySeries")

' Set the chart type (Line, Bar, Pie, etc.)


[Link]("MySeries").ChartType =
[Link]

' Add data points to the chart


[Link]("MySeries").[Link](0, 5)
[Link]("MySeries").[Link](1, 8)
[Link]("MySeries").[Link](2, 3)
[Link]("MySeries").[Link](3, 10)
[Link]("MySeries").[Link](4, 7)

This simple [Link] example adds a line chart with five data points. More complex examples
such as mul ple series, axis tles, legends, or data binding can be added as needed.
Homework:
Create a graphical user interface (GUI) for a WinForms applica on to input data of the grain
size distribu on test.

85 BAKHTI RACHID
Chapter III: Graphical user interface development

III.4. Tkinter Version (Python)


Tkinter is Python’s standard library for creating graphical user interfaces (GUI). Unlike WinForms,
Tkinter does not have a drag-and-drop designer in standard Python IDEs, but you can still build
fully functional GUI applications programmatically. Key components of a Tkinter application
include:

 Widgets: UI elements like buttons, labels, text entries, checkboxes, and menus.
 Windows: The main application window (Tk) or additional windows (Toplevel).
 Geometry Managers: Tools like pack(), grid(), and place() to arrange widgets inside a
window.
 Event Handling: Binding functions to user actions such as clicks, keypresses, or mouse
movements.
 Variables: Tkinter supports StringVar, IntVar, DoubleVar, and BooleanVar for dynamic
widget content.

III.4.1. Components of a Tkinter Applica on


 Root Window: The main application window created using root = Tk().
 Widgets: Buttons, Labels, Entry (TextBox), Listbox, Checkbutton, Radiobutton, Menu,
Text, Canvas, Scale, Progressbar, and more.
 Frames: Containers similar to Panels or GroupBoxes, used to organize widgets.
 Classes and Functions: Used to organize the application logic and encapsulate
functionality.
 Event Handlers: Functions bound to widget events like command for buttons or bind for
key/mouse events.
 Menus: Tkinter supports top-level menus (Menu) and context menus ([Link] with
post method).
 Variables: Special Tkinter variables (StringVar, IntVar) allow automatic updates between
widgets and Python code.

86 BAKHTI RACHID
Chapter III: Graphical user interface development

III.4.2. Toolbox Components (Widgets in Tkinter)


Widget Descrip on
Bu on Trigger an ac on when clicked.
Label Display text or instruc ons.
Entry Input text from the user (similar to TextBox).
Text Mul -line text input/display (similar to RichTextBox).
Combobox ( k) Drop-down list for selec on.
Listbox Display a list of items; mul ple selec on possible.
Radiobu on Choose one op on from a group.
Checkbu on Toggle a binary choice.
Frame Container for grouping widgets.
Canvas Draw shapes, charts, or images.
Menu Create a top-level menu bar.
Popup Menu Context menu on right-click.
Scale Slider for numeric input.
Progressbar ( k) Show progress of a task.
Treeview ( k) Display hierarchical or tabular data.
Spinbox Numeric or list selec on box.
Notebook ( k) Tabbed interface.
Messagebox Display alert/info dialogs.

III.4.3. Menu and Context Menu


Menus in Tkinter allow users to access application functions easily. Tkinter supports top-level
menus (Menu) and context menus (right-click menus).

 Top-level Menu (Menu):


Appears at the top of the main window. Example: File → New, Open, Save.

87 BAKHTI RACHID
Chapter III: Graphical user interface development

 Context Menu (Popup Menu):


Appears when the user right-clicks a widget. Implemented with [Link] and .post(x, y).

Example: Top-level Menu and Context Menu

import tkinter as tk
from tkinter import messagebox
root = [Link]()
[Link]("Menu Example")
# Top-level menu
menubar = [Link](root)
file_menu = [Link](menubar, tearoff=0)
file_menu.add_command(label="New", command=lambda: [Link]("Menu",
"New File"))
file_menu.add_command(label="Open", command=lambda: [Link]("Menu",
"Open File"))
file_menu.add_separator()
file_menu.add_command(label="Save", command=lambda: [Link]("Menu",
"Save File"))
menubar.add_cascade(label="File", menu=file_menu)
[Link](menu=menubar)
# Context menu
context_menu = [Link](root, tearoff=0)
context_menu.add_command(label="Option 1")
context_menu.add_command(label="Option 2")
def show_context(event):
context_menu.post(event.x_root, event.y_root)
[Link]("<Button-3>", show_context) # Right-click
[Link]()

III.4.4. Entry (TextBox)


The Entry widget in Tkinter allows single-line text input. For multi-line input, Tkinter provides
the Text widget.

Key Features:

88 BAKHTI RACHID
Chapter III: Graphical user interface development

 Single-line or multi-line input


 Password masking using show="*"
 Limit input length via validation
 Event handling for TextChanged equivalent using trace on StringVar

import tkinter as tk
root = [Link]()
[Link]("Entry Example")
label = [Link](root, text="Enter your name:")
[Link]()
entry = [Link](root)
[Link]()
def show_input():
[Link](text="You entered: " + [Link]())

button = [Link](root, text="Submit", command=show_input)


[Link]()
[Link]()

III.4.5. Label
The Label widget displays text, images, or both. Labels are read-only and often used to describe
other widgets or show output dynamically.

Key Features:

 Display static or dynamic text


 Customize font, color, size, alignment
 Support for multi-line text

import tkinter as tk
root = [Link]()
[Link]("Label Example")
label = [Link](root, text="Hello, this is a Label!", font=("Arial", 12, "bold"), fg="blue")
[Link]()
def update_label():

89 BAKHTI RACHID
Chapter III: Graphical user interface development

[Link](text="You clicked the button!")

button = [Link](root, text="Click Me", command=update_label)


[Link]()
[Link]()

III.4.6. Treeview (DataGridView Equivalent)


[Link] is Tkinter’s data grid widget for displaying tabular data.

Key Features:

 Multiple columns with headers


 Insert, read, and update cell values
 Support for hierarchical data

import tkinter as tk
from tkinter import ttk
root = [Link]()
[Link]("Treeview Example")
# Treeview with columns
tree = [Link](root, columns=("ID", "Name", "Value"), show='headings')
[Link]("ID", text="ID")
[Link]("Name", text="Name")
[Link]("Value", text="Value")
[Link]()
# Insert rows
[Link]("", [Link], values=(1, "Item A", 12.5))
[Link]("", [Link], values=(2, "Item B", 18.9))
[Link]("", [Link], values=(3, "Item C", 7.3))

# Read a cell value


first_row = [Link](tree.get_children()[0])['values']
print("First row Value:", first_row[2])
# Update a cell value
[Link](tree.get_children()[1], column="Name", value="Updated Item B")

[Link]()

90 BAKHTI RACHID
Chapter III: Graphical user interface development

III.4.7. Chart (Matplotlib + Tkinter)


Tkinter does not have a built-in chart widget. Charts are created using Matplotlib and
embedded in Tkinter windows with FigureCanvasTkAgg.

Key Features:

 Line, bar, pie, scatter, area charts


 Interactive updates
 Full customization (titles, axes, colors, legends)

import tkinter as tk
from [Link].backend_tkagg import FigureCanvasTkAgg
from [Link] import Figure
root = [Link]()
[Link]("Chart Example")
# Matplotlib Figure
fig = Figure(figsize=(5, 4))
ax = fig.add_subplot(111)
# Sample Data
x = [0, 1, 2, 3, 4]
y = [5, 8, 3, 10, 7]
[Link](x, y, marker='o', linestyle='-', color='blue')
ax.set_title("Line Chart Example")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
# Embed Figure in Tkinter
canvas = FigureCanvasTkAgg(fig, master=root)
[Link]()
canvas.get_tk_widget().pack()
[Link]()

Homework

Create a Tkinter GUI for grain size distribution test:

91 BAKHTI RACHID
Chapter III: Graphical user interface development

1. Labels and Entry widgets for user input


2. Button to submit and display data
3. Treeview to show tabular results
4. Optional: Matplotlib chart to visualize the distribution

III.5. Events handling


Event handling is one of the most essential concepts in graphical user interface (GUI)
programming. A GUI application is interactive by nature: instead of executing a sequence of
instructions from start to finish, it waits for the user to perform actions and then responds
accordingly. These actions—such as clicking a button, typing text, selecting an item, resizing a
window, or moving the mouse—are called events. When an event occurs, the program must
“handle” it by executing specific code associated with that event. This process is known as event
handling.

In a GUI environment, almost everything is event-driven. The application remains idle until the
user interacts with a control (button, textbox, chart, etc.) or sends input through the keyboard or
mouse. Each control exposes a set of events, allowing developers to customize how the
application behaves. For example, a button may trigger a Click event, a TextBox may trigger a
TextChanged event whenever its content is modified, and a DataGridView may react to CellClick
or SelectionChanged events. Mastering event handling enables developers to create responsive,
dynamic, and user-friendly applications.

Both WinForms ([Link]) and Tkinter (Python) implement event handling, but they do so using
different syntaxes and mechanisms. In WinForms, events are typically handled using the Handles
keyword or the AddHandler statement. Each event is tied to a method—called an event handler—
that contains the actions to be executed when that event occurs. For example, writing Handles
[Link] automatically connects the method to the Click event of a specific button.
WinForms also supports a wide variety of advanced events such as mouse position tracking,

92 BAKHTI RACHID
Chapter III: Graphical user interface development

keyboard shortcuts, form lifecycle events (load, closing), and data-related events (grid selection,
value changes).

Tkinter, on the other hand, uses a different style of event handling. Basic controls like Buttons use
the command= parameter to link a function directly to a click action. For more complex events,
such as keyboard input or mouse interactions, Tkinter uses the bind() method, which attaches
events to functions using event codes like <Button-1>, <KeyRelease>, or <Motion>. Tkinter also
relies heavily on "callbacks": functions that the framework calls automatically when an event
occurs. This model gives developers fine-grained control over user interactions and custom
behavior.

Understanding event handling is crucial because it forms the backbone of how GUI software
operates. Without events, programs cannot react to user input, making interaction impossible.
Whether the goal is to create a simple form that updates labels based on user input, build data-
entry applications, or design advanced engineering software with dynamic charts and
visualization tools, event-driven logic is always at the core.

In summary, event handling allows your application to:

 React to user interactions such as clicks, keystrokes, and selections


 Update the user interface dynamically
 Control the program’s behavior in response to real-time input
 Implement validation, navigation, and custom interactions
 Build responsive and interactive applications for engineering tasks

Although WinForms and Tkinter handle events differently, the underlying principles remain the
same. A user action triggers an event, the event is captured by the application, and the
corresponding handler executes the appropriate response. Mastering these concepts is essential
for developing robust and intuitive GUI applications in both [Link] and Python.

93 BAKHTI RACHID
Chapter III: Graphical user interface development

III.5.1. Event Handling in WinForms ([Link])


In WinForms, events are handled using the Handles keyword or by adding handlers manually with
AddHandler. Each control exposes many events such as:

 Click
 TextChanged
 SelectedIndexChanged
 CellClick
 FormClosing
 MouseMove
 etc.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles [Link]


[Link]("Button clicked!")
End Sub
Example 1 — Button Click Event

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles


[Link]
[Link] = "You typed: " & [Link]
End Sub
Example 2 — TextChanged Event (TextBox)

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs)


Handles [Link]
Dim value As String
value = [Link]([Link]).Cells([Link]).[Link]()
[Link]("Cell value: " & value)
End Sub
Example 3 — Cell Click Event (DataGridView)

94 BAKHTI RACHID
Chapter III: Graphical user interface development

III.5.2. Event Handling in Tkinter (Python)


Tkinter uses the command= parameter (for buttons and menus) or the bind() method to attach
events. Common Tkinter events:

 <Button-1> — Left mouse click


 <KeyRelease> — Key released
 <Double-Button-1> — Double click
 <Motion> — Mouse move
 <Return> — Enter key
 <<TreeviewSelect>> — Treeview row selected

import tkinter as tk
root = [Link]()
def on_click():
print("Button clicked!")
button = [Link](root, text="Click Me", command=on_click)
[Link]()
[Link]()
Example 1 — Button Click Event
Tkinter does not have a na ve TextChanged event,
but we can use a StringVar with trace():
import tkinter as tk

root = [Link]()

def text_changed(*args):
print("You typed:", text_var.get())

text_var = [Link]()
text_var.trace("w", text_changed)

entry = [Link](root, textvariable=text_var)


[Link]()

[Link]()
Example 2 — Detec ng Text Change in Entry

95 BAKHTI RACHID
Chapter III: Graphical user interface development

import tkinter as tk
from tkinter import k
root = [Link]()

tree = [Link](root, columns=("Name", "Age"), show='headings')


[Link]("Name", text="Name")
[Link]("Age", text="Age")
[Link]()

[Link]("", [Link], values=("Mohamed", 28))


[Link]("", [Link], values=("Ali", 24))

def on_row_selected(event):
selected = [Link] on()
value = [Link](selected)['values']
print("Selected row:", value)

[Link]("<<TreeviewSelect>>", on_row_selected)

[Link]()
Example 3 — Treeview Row Selec on Event

96 BAKHTI RACHID

You might also like