搜尋
首頁後端開發Python教學誰說Python寫GUI程式醜?那是你不會美化!

誰說Python寫GUI程式醜?那是你不會美化!

在平時工作學習當中,我們經常會寫一些簡單的Python GUI 工具,以此來完成各種各樣的自動化任務,例如批量處理文件,批量處理圖片等等。當我們進行這些工具的編寫之時,往往只關注了功能的實現,而忽略了頁面的美化,這也使得在人們的眼中,Python 構建的GUI 程序都是比較low 的,今天我們先忽略掉功能,著眼於頁面的美化,來看看純Python 的編寫的GUI 程式也可以很美觀!

頁面佈局

我們先完成一個基本的GUI 佈局

假設我們想要做一個進位轉換的工具,那麼大致的佈局如下圖:

誰說Python寫GUI程式醜?那是你不會美化!

上圖是完全透過Python 自帶的GUI 函式庫tkinter 來寫的。

部分程式碼如下:

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()

程式碼並不複雜,佈局也是使用的最基本的pack 方式,整個GUI 程式雖然看起來比較整齊,但是顏色單調,各個元件也不是十分美觀,下面我們就來進行美化。

頁面美化

我們先透過手動設定 CSS 的方式來美化頁面,這裡主要用到了 tkonter 函式庫的 config 屬性。

首先我們設定背景顏色:

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

對於整體container 容器,我們設定背景色為#073642

##接下來再分別設定各個元件的樣式:

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')

都是透過config 來設置,對於顏色的選擇,可以透過線上的顏色選擇器來選擇。


     https://tools.kalvinbg.cn/dev/colorPicker 接下來我們進行下拉框樣式的設置,對於下拉框元件,還是有些特殊的。

該元件屬於ttk 元件,所以設定樣式需要透過主題來進行,程式碼如下:

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')

這樣我們整體GUI 程式的樣式就設定完成了,來看下最終的效果:


誰說Python寫GUI程式醜?那是你不會美化!

可以明顯看出,顏值那是提升了好幾個檔次!


使用 ttkbootstrap 美化頁面


當然我們還有更簡單有效的美化方法,就是使用 ttkbootstrap 函式庫來進行頁面美化。


首先透過pip 安裝ttkbootstrap 函式庫:


pip install ttkbootstrap

然後在專案中引用該函式庫:

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

此時當我們完成元件的佈局的時候,頁面整體風格也就變成了主題solar的樣式了,當然我們還是可以為不同的元件添加bootstyle屬性來達到更多樣式效果。

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)

最終效果如下:


誰說Python寫GUI程式醜?那是你不會美化!

可以看出,使用該庫的整體效果還是要比我們手工添加CSS 樣式要更加美觀,同時也更加便捷!


好了,這就是今天分享的全部內容,我們下次再見~

以上是誰說Python寫GUI程式醜?那是你不會美化!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:51CTO.COM。如有侵權,請聯絡admin@php.cn刪除
Python腳本可能無法在UNIX上執行的一些常見原因是什麼?Python腳本可能無法在UNIX上執行的一些常見原因是什麼?Apr 28, 2025 am 12:18 AM

Python腳本在Unix系統上無法運行的原因包括:1)權限不足,使用chmod xyour_script.py賦予執行權限;2)Shebang行錯誤或缺失,應使用#!/usr/bin/envpython;3)環境變量設置不當,可打印os.environ調試;4)使用錯誤的Python版本,可在Shebang行或命令行指定版本;5)依賴問題,使用虛擬環境隔離依賴;6)語法錯誤,使用python-mpy_compileyour_script.py檢測。

舉一個場景的示例,其中使用Python數組比使用列表更合適。舉一個場景的示例,其中使用Python數組比使用列表更合適。Apr 28, 2025 am 12:15 AM

使用Python數組比列表更適合處理大量數值數據。 1)數組更節省內存,2)數組對數值運算更快,3)數組強制類型一致性,4)數組與C語言數組兼容,但在靈活性和便捷性上不如列表。

在Python中使用列表與數組的性能含義是什麼?在Python中使用列表與數組的性能含義是什麼?Apr 28, 2025 am 12:10 AM

列表列表更好的forflexibility andmixDatatatypes,何時出色的Sumerical Computitation sand larged數據集。 1)不可使用的列表xbilese xibility xibility xibility xibility xibility xibility xibility xibility xibility xibility xibles and comply offrequent elementChanges.2)

Numpy如何處理大型數組的內存管理?Numpy如何處理大型數組的內存管理?Apr 28, 2025 am 12:07 AM

numpymanagesmemoryforlargearraysefefticefticefipedlyuseviews,副本和內存模擬文件.1)viewsAllowSinglicingWithOutCopying,直接modifytheoriginalArray.2)copiesCanbecopy canbecreatedwitheDedwithTheceDwithThecevithThece()methodervingdata.3)metservingdata.3)memore memore-mappingfileShessandAstaStaStstbassbassbassbassbassbassbassbassbassbassbb

哪個需要導入模塊:列表或數組?哪個需要導入模塊:列表或數組?Apr 28, 2025 am 12:06 AM

Listsinpythondonotrequireimportingamodule,helilearraysfomthearraymoduledoneedanimport.1)列表列表,列表,多功能和canholdMixedDatatatepes.2)arraysaremoremoremoremoremoremoremoremoremoremoremoremoremoremoremoremoremeremeremeremericdatabuteffeftlessdatabutlessdatabutlessfiblesible suriplyElsilesteletselementEltecteSemeTemeSemeSemeSemeTypysemeTypysemeTysemeTypysemeTypepe。

可以在Python數組中存儲哪些數據類型?可以在Python數組中存儲哪些數據類型?Apr 27, 2025 am 12:11 AM

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Python標準庫的哪一部分是:列表或數組?Python標準庫的哪一部分是:列表或數組?Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器