Table of Contents
Page beautification
Use ttkbootstrap to beautify the page
Home Backend Development Python Tutorial Who 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!

Apr 11, 2023 pm 01:52 PM
python gui

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()
Copy after login

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')
Copy after login

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')
Copy after login

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')
Copy after login

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
Copy after login

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))# 设置一个主题
Copy after login

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)
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles