search
HomeBackend DevelopmentPython TutorialWho said writing GUI programs in Python is ugly? That's because you don't know how to beautify it!

Who said writing GUI programs in Python is ugly? That's because you don't know how to beautify it!

In our daily work and study, we often write some simple Python GUI tools to complete various automated tasks, such as batch processing of files, batch processing of pictures, etc. wait. When we write these tools, we often only focus on the implementation of functions and ignore the beautification of the page. This also makes the GUI programs built in Python relatively low in people's eyes. Today we will ignore the functions first. , focusing on page beautification, let’s see how beautiful GUI programs written in pure Python can be!

Page layout

We first complete a basic GUI layout

Suppose we want to make a hexadecimal conversion tool, then The general layout is as follows:

Who said writing GUI programs in Python is ugly? That's because you don't know how to beautify it!

The above picture is completely written through tkinter, the GUI library that comes with Python.

Part of the code is as follows:

from tkinter import ttk
from tkinter import *
class Transform():
 def __init__(self):
 self.root = Tk()
 self.root.title("进制转换工具")
 self.root.geometry("600x280")
 self.root.resizable(False, False)
 self.var = StringVar()
 self.values = ['2', '8', '10', '16', '32', '36', '58', '62']
 self.myWidget()
 self.myLayout()
 def myWidget(self):
 self.container = Frame(self.root)
 # 转换设置区域
 self.lf_group1 = LabelFrame(master=self.container, text="转换设置")
 self.cb = Checkbutton(self.lf_group1, text="是否自动转换")
 self.cb.invoke()
 self.bt = Button(self.lf_group1, text='转换')
 self.en = Entry(self.lf_group1, text='warning')
 # 进制选择区域
 self.lf_group2 = LabelFrame(master=self.container, text="进制选择")
 self.lb1 = Label(self.lf_group2, text="请选择待转换的进制")
 self.cbo1 = ttk.Combobox(
 master=self.lf_group2,
 values=self.values
 )
 self.cbo1.set(self.values[2])
 self.lb2 = Label(self.lf_group2, text="请选择转换后的进制")
 self.cbo2 = ttk.Combobox(
 master=self.lf_group2,
 values=self.values,
 )
 self.cbo2.set(self.values[0])
 # 进制输出区域
 self.txt = Text(master=self.container, height=5, width=50)
 def myLayout(self):
 self.container.pack(side=LEFT, fill=BOTH, expand=YES, padx=5)
 self.lf_group1.pack(fill=X, side=TOP)
 self.lf_group2.pack(fill=X, pady=10, side=TOP)
 self.cb.pack(side=LEFT, expand=YES, padx=5, fill=X)
 self.bt.pack(side=LEFT, expand=YES, padx=5, fill=X)
 self.en.pack(side=LEFT, expand=YES, padx=5, fill=X)
 self.lb1.pack(side=LEFT, expand=YES, padx=5)
 self.cbo1.pack(side=LEFT, expand=YES, pady=5)
 self.lb2.pack(side=LEFT, expand=YES, padx=5)
 self.cbo2.pack(side=LEFT, expand=YES, pady=5)
 self.txt.pack(side=LEFT, anchor=NW, pady=5, fill=BOTH, expand=YES)
 def run(self):
 self.container.mainloop()
if __name__ == '__main__':
 trans = Transform()
 trans.run()

The code is not complicated, and the layout is also the most basic pack method used. Although the entire GUI program looks relatively neat, the colors are monotonous and each component It’s not very beautiful either, so let’s beautify it next.

Page beautification

We first beautify the page by manually setting CSS. Here we mainly use the config attribute of the tkonter library.

First we set the background color:

self.container.config(bg='#073642')

For the overall container container, we set the background color to #073642

Then we will separately Set the style of each component:

self.lf_group1.config(bg='#073642', fg="white")
self.lf_group2.config(bg='#073642', fg="white")
self.cb.config(bg='#073642', selectcolor='#073642', activebackground='#073642',
activeforeground='#073642', fg="white")
self.bt.config(bg="azure3")
self.en.config(highlightbackground="#0b5162", highlightcolor="#0b5162",
insertofftime=500, insertontime=500, fg="Gainsboro", insertbackground="Gainsboro",
bg="#073642", highlightthickness=2, relief="solid")
self.lb1.config(bg='#073642', activebackground='#073642',
 activeforeground='#073642', fg="white")
self.lb2.config(bg='#073642', activebackground='#073642',
 activeforeground='#073642', fg="white")
self.txt.config(insertofftime=500, insertontime=500, fg="Gainsboro", insertbackground="Gainsboro",
 wrap="none", bg='#073642')

is set through config. For color selection, you can choose through the online color selector.

  • https://tools.kalvinbg.cn/dev/colorPicker Next we set the drop-down box style. There are some special things about the drop-down box component.

This component belongs to the ttk component, so setting the style needs to be done through the theme. The code is as follows:

combostyle = ttk.Style()
combostyle.theme_create('combostyle', parent='alt',
 settings={'TCombobox':
 {'configure':
 {
 'foreground': 'white',
 'selectbackground': '#073642',# 选择后的背景颜色
 'fieldbackground': '#073642',# 下拉框颜色
 'background': '#073642',# 下拉按钮背景颜色
 "font": 10,# 字体大小
 }}}
 )
combostyle.theme_use('combostyle')

In this way, the style of our overall GUI program is set. Let’s Take a look at the final effect:

Who said writing GUI programs in Python is ugly? That's because you don't know how to beautify it!

It can be clearly seen that the appearance has been improved by several levels!

Use ttkbootstrap to beautify the page

Of course we have a simpler and more effective beautification method, which is to use the ttkbootstrap library to beautify the page.

First install the ttkbootstrap library through pip:

pip install ttkbootstrap

Then reference the library in the project:

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
class MainCreator(ttk.Window):
 def __init__(self):
 super().__init__("进制转换工具", themename="solar", resizable=(False, False))# 设置一个主题

At this time when we complete the layout of the components At that time, the overall style of the page has become the style of the theme solar. Of course, we can still add bootstyle attributes to different components to achieve more style effects.

def create_frame(self):
 """Create all the frame widgets"""
 container = ttk.Frame(self)
 container.pack(side=LEFT, fill=BOTH, expand=YES, padx=5)
 color_group = ttk.Labelframe(
 master=container, text="转换设置", padding=10
 )
 color_group.pack(fill=X, side=TOP)
 self.cb = ttk.Checkbutton(color_group, text="是否自动转换", variable=self.cbvar)
 self.cb.invoke()
 self.bt = ttk.Button(color_group, text='转换', bootstyle='success')
 self.en = ttk.Entry(color_group, text='warning', bootstyle='warning')
 self.cb.pack(side=LEFT, expand=YES, padx=5, fill=X)
 self.bt.pack(side=LEFT, expand=YES, padx=5, fill=X)
 self.en.pack(side=LEFT, expand=YES, padx=5, fill=X)
 cr_group = ttk.Labelframe(
 master=container, text="进制选择", padding=10
 )
 cr_group.pack(fill=X, pady=10, side=TOP)
 values = ['2', '8', '10', '16', '32', '36', '58', '62']
 cr3 = ttk.Label(cr_group, text="请选择待转换的进制")
 cr3.pack(side=LEFT, expand=YES, padx=5)
 self.cbo1 = ttk.Combobox(
 master=cr_group,
 values=values,
 )
 self.cbo1.pack(side=LEFT, expand=YES, pady=5)
 self.cbo1.set(values[2])
 cr5 = ttk.Label(cr_group, text="请选择转换后的进制")
 cr5.pack(side=LEFT, expand=YES, padx=5)
 self.cbo2 = ttk.Combobox(
 master=cr_group,
 values=values,
 )
 self.cbo2.pack(side=LEFT, expand=YES, pady=5)
 self.cbo2.set(values[0])
 self.txt = ttk.Text(master=container, height=5, width=50, wrap="none")
 self.txt.pack(side=LEFT, anchor=NW, pady=5, fill=BOTH, expand=YES)

The final effect is as follows:

Who said writing GUI programs in Python is ugly? That's because you don't know how to beautify it!

It can be seen that the overall effect of using this library is still more beautiful than adding CSS styles manually. , and also more convenient!

Okay, this is all the content shared today, see you next time~

The above is the detailed content of Who said writing GUI programs in Python is ugly? That's because you don't know how to beautify it!. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software