Home  >  Article  >  Backend Development  >  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!

王林
王林forward
2023-04-11 13:52:031901browse

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