Table of Contents
Theme Switch
Some simple introduction to the use of ttkbootstrap
Tag
Button
Input box
Text Box
Date input
Radio button
Multi-select button
Combo box
Frame and Labelframe
Meter
Progress bar
Scale
Water ruler
Scroll bar
Message prompt Box
Query box
Subwindow
Menu
Panel
Tree View
加载gif动图
打开本地文件
打开浏览器
Home Backend Development Python Tutorial How to use ttkbootstrap to create a beautiful interface for Python GUI?

How to use ttkbootstrap to create a beautiful interface for Python GUI?

May 07, 2023 pm 03:40 PM
python gui tkinter

These two pictures are screenshots of the display renderings provided on the official website:

How to use ttkbootstrap to create a beautiful interface for Python GUI?

How to use ttkbootstrap to create a beautiful interface for Python GUI?

Theme Switch

Simple theme switching, since there are few components on the current window, the effect is not obvious, but it will look good when there are many components in the layout.

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
style = ttk.Style()
theme_names = style.theme_names()#以列表的形式返回多个主题名
theme_selection = ttk.Frame(root, padding=(10, 10, 10, 0))
theme_selection.pack(fill=X, expand=YES)
lbl = ttk.Label(theme_selection, text="选择主题:")
theme_cbo = ttk.Combobox(
        master=theme_selection,
        text=style.theme.name,
        values=theme_names,
)
theme_cbo.pack(padx=10, side=RIGHT)
theme_cbo.current(theme_names.index(style.theme.name))
lbl.pack(side=RIGHT)
def change_theme(event):
    theme_cbo_value = theme_cbo.get()
    style.theme_use(theme_cbo_value)
    theme_selected.configure(text=theme_cbo_value)
    theme_cbo.selection_clear()
theme_cbo.bind(&#39;<<ComboboxSelected>>&#39;, change_theme)
theme_selected = ttk.Label(
        master=theme_selection,
        text="litera",
        font="-size 24 -weight bold"
)
theme_selected.pack(side=LEFT)
root.mainloop()
Copy after login

Some simple introduction to the use of ttkbootstrap

First of all, some brief introduction to its instantiation and creation of application windows.

import ttkbootstrap as ttk
#实例化创建应用程序窗口
root = ttk.Window(
        title="窗口名字",        #设置窗口的标题
        themename="litera",     #设置主题
        size=(1066,600),        #窗口的大小
        position=(100,100),     #窗口所在的位置
        minsize=(0,0),          #窗口的最小宽高
        maxsize=(1920,1080),    #窗口的最大宽高
        resizable=None,         #设置窗口是否可以更改大小
        alpha=1.0,              #设置窗口的透明度(0.0完全透明)
        )
# root.place_window_center()    #让显现出的窗口居中
# root.resizable(False,False)   #让窗口不可更改大小
# root.wm_attributes(&#39;-topmost&#39;, 1)#让窗口位置其它窗口之上
root.mainloop()
Copy after login

Tag

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
ttk.Label(root,text="标签1",bootstyle=INFO).pack(side=ttk.LEFT, padx=5, pady=10)
ttk.Label(root,text="标签2",boot).pack(side=ttk.LEFT, padx=5, pady=10)
ttk.Label(root,text="标签3",boot).pack(side=ttk.LEFT, padx=5, pady=10)
ttk.Label(root, text="标签4", bootstyle=WARNING, font=("微软雅黑", 15), background=&#39;#94a2a4&#39;).pack(side=LEFT, padx=5, pady=10)
root.mainloop()
&#39;&#39;&#39;
# bootstyle colors
PRIMARY = &#39;primary&#39;
SECONDARY = &#39;secondary&#39;
SUCCESS = &#39;success&#39;
DANGER = &#39;danger&#39;
WARNING = &#39;warning&#39;
INFO = &#39;info&#39;
LIGHT = &#39;light&#39;
DARK = &#39;dark&#39;

# bootstyle types
OUTLINE = &#39;outline&#39;
LINK = &#39;link&#39;
TOGGLE = &#39;toggle&#39;
INVERSE = &#39;inverse&#39;
STRIPED = &#39;striped&#39;
TOOLBUTTON = &#39;toolbutton&#39;
ROUND = &#39;round&#39;
SQUARE = &#39;square&#39;
&#39;&#39;&#39;
Copy after login

Button

Button style:

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
ttk.Button(root, text="Button 1", bootstyle=SUCCESS).pack(side=LEFT, padx=5, pady=10)
ttk.Button(root, text="Button 2", bootstyle=(INFO, OUTLINE)).pack(side=LEFT, padx=5, pady=10)
ttk.Button(root, text="Button 3", bootstyle=(PRIMARY, "outline-toolbutton")).pack(side=LEFT, padx=5, pady=10)
ttk.Button(root, text="Button 4", boot).pack(side=LEFT, padx=5, pady=10)
ttk.Button(root, text="Button 5", boot).pack(side=LEFT, padx=5, pady=10)
ttk.Button(root, text="Button 6", state="disabled").pack(side=LEFT, padx=5, pady=10) #在禁用状态下创建按钮
root.mainloop()
Copy after login

Button click:

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
#为按钮添加点击事件
#法一
def button1():
    print("Button1点击了一下!")
ttk.Button(root,text="Button1", bootstyle=(PRIMARY, "outline-toolbutton"),command=button1).pack(side=LEFT, padx=5, pady=10)
#法二
def button2(event): #这里要加一个参数,不然会报错
    print("Button2点击了一下!")
    button_text = event.widget["text"] #得到按钮上的文本
    print(button_text)
b = ttk.Button(root,text="Button2", bootstyle=(PRIMARY, "outline-toolbutton"))
b.pack(side=LEFT, padx=5, pady=10)
b.bind("<Button-1>", button2) #<Button-1>鼠标左键
root.mainloop()
Copy after login

Input box

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
e1 = ttk.Entry(root,show=None)
e1.insert(&#39;0&#39;,"默认插入内容")
e1.grid(row=5, column=1, sticky=ttk.W, padx=10,pady=10)
e2 = ttk.Entry(root,show="*",width=50,bootstyle=PRIMARY)
e2.grid(row=10, column=1, sticky=ttk.W, padx=10, pady=10)
e3_content = ttk.StringVar()
e3 = ttk.Entry(root,bootstyle=&#39;success&#39;, textvariable=e3_content).grid(row=15, column=1, sticky=ttk.W, padx=10, pady=10)
def get_entry_contetn():
    print("e1: ",e1.get())
    print("e2: ",e2.get())
    print("e3: ",e3_content.get())
ttk.Button(root,text="get_entry_contetn", bootstyle=(PRIMARY, "outline-toolbutton"),command=get_entry_contetn).grid(row=20, column=1, sticky=ttk.W, padx=10, pady=10)
root.mainloop()
Copy after login

Text Box

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
text = ttk.Text(root,)
text.pack(padx=10,pady=10,fill=BOTH)
text.insert(&#39;insert&#39;,&#39;text-content 1&#39;) #插入内容
text.delete("0.0",&#39;end&#39;) #删除内容
text.insert(&#39;insert&#39;,&#39;text-content 2\npy&#39;)
text.see(ttk.END) #光标跟随着插入的内容移动
root.mainloop()
Copy after login

Date input

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
de1 = ttk.DateEntry()
de1.grid(row=6, column=1, sticky=ttk.W,padx=10, pady=10)
print(de1.entry.get())

de2 = ttk.DateEntry(boot,dateformat=r"%Y") #r"%Y-%m-%d"
de2.grid(row=6, column=2, sticky=ttk.W,padx=10, pady=10)
def get_dataentry():
    print(de2.entry.get())
ttk.Button(root,text="get_dataentry", bootstyle=(PRIMARY, "outline-toolbutton"),command=get_dataentry).grid(row=20, column=1, sticky=ttk.W, padx=10, pady=10)
root.mainloop()
Copy after login

Radio button

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
root = ttk.Window()
variable_value = ttk.StringVar()
variable_value_dist = {
    "0":"男",
    "1":"女",
    "2":"未知"
}
ttk.Radiobutton(root, text=&#39;男&#39;, variable=variable_value, value=0).pack(side=ttk.LEFT, padx=5)
ttk.Radiobutton(root, text=&#39;女&#39;, variable=variable_value, value=1).pack(side=ttk.LEFT, padx=5)
ttk.Radiobutton(root, text=&#39;未知&#39;, variable=variable_value, value=2).pack(side=ttk.LEFT, padx=5)
def ensure():
    print(variable_value_dist[variable_value.get()])
ttk.Button(text="确定", command=ensure).pack(side=ttk.LEFT, padx=5)
root.mainloop()
Copy after login

Multi-select button

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
root = ttk.Window()
variable_content = [
    [ttk.StringVar(),"111"],
    [ttk.StringVar(),"222"],
    [ttk.StringVar(),"333"],
    [ttk.StringVar(),"666"]
]
ttk.Checkbutton(root, text="111", variable=variable_content[0][0]).pack(side=ttk.LEFT, padx=5)
ttk.Checkbutton(root, text="222", variable=variable_content[1][0], boot).pack(side=ttk.LEFT, padx=5)
ttk.Checkbutton(root, text="333", variable=variable_content[2][0], boot).pack(side=ttk.LEFT, padx=5)
ttk.Checkbutton(root, text="666", variable=variable_content[3][0]).pack(side=ttk.LEFT, padx=5)
def ensure():
    print([v for i, v in variable_content if i.get()])
ttk.Button(text="确定",command=ensure).pack(side=ttk.LEFT, padx=5)
root.mainloop()
Copy after login

Combo box

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
cbo = ttk.Combobox(
            master=root,
            bootstyle = DANGER,
            font = ("微软雅黑",12),
            values=[&#39;content 1&#39;, &#39;content 2&#39;, &#39;content 3&#39;],
        )
cbo.current(1) #首先展示values里面索引的对应的值
cbo.pack()
# cbo.set(&#39;set other&#39;)
def ensure(event):
    print(cbo.get())
cbo.bind(&#39;<<ComboboxSelected>>&#39;, ensure)
root.mainloop()
Copy after login

Frame and Labelframe

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
f = ttk.Frame(bootstyle=SUCCESS)
f.place(x=10,y=10,width=600,height=200)

lf = ttk.Labelframe(text="提示",bootstyle=PRIMARY,width=100,height=60)
lf.place(x=10,y=210,width=300,height=100)
ttk.Label(lf,text="标签").pack()
ttk.Button(lf,text="按钮").pack()
root.mainloop()
Copy after login

Meter

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import psutil,time,threading
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
ttk.Meter(
        master=root,
        bootstyle=DEFAULT,
        metertype="full",#将仪表显示为一个完整的圆形或半圆形(semi)
        wedgesize=5, #设置弧周围的指示器楔形长度,如果大于 0,则此楔形设置为以当前仪表值为中心的指示器
        amounttotal=50, #仪表的最大值,默认100
        amountused=10, #仪表的当前值
        metersize=200,#仪表大小
        showtext=True, #指示是否在仪表上显示左、中、右文本标签
        interactive=True, #是否可以手动调节数字的大小
        textleft=&#39;左边&#39;, #插入到中心文本左侧的短字符串
        textright=&#39;右边&#39;,
        textfont="-size 30", #中间数字大小
        subtext="文本",
        subtextstyle=DEFAULT,
        subtextfont="-size 20",#文本大小
        ).pack(side=ttk.LEFT, padx=5)
def _():
        meter = ttk.Meter(
                metersize=180,
                padding=50,
                amountused=0,
                metertype="semi",
                subtext="当前网速(kB/s)",
                subtext,
                interactive=False,
                bootstyle=&#39;primary&#39;,
                )
        meter.pack(side=ttk.LEFT, padx=5)
        while True:
                meter.configure(amountused=round(getNet(),2))
def getNet():
    recv_before = psutil.net_io_counters().bytes_recv
    time.sleep(1)
    recv_now = psutil.net_io_counters().bytes_recv
    recv = (recv_now - recv_before)/1024
    return recv

t = threading.Thread(target=_)
t.setDaemon(True)
t.start()
root.mainloop()
Copy after login

Progress bar

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import time,threading
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window(size=(500,380))
def _():
    f = ttk.Frame(root).pack(fill=BOTH, expand=YES)
    p1 = ttk.Progressbar(f, bootstyle=PRIMARY)
    p1.place(x=20, y=20, width=380, height=40)
    p1.start() #间隔默认为50毫秒(20步/秒)
    p2 = ttk.Progressbar(f, bootstyle=INFO,orient=VERTICAL)
    p2.place(x=200, y=100, width=40, height=200)
    p2.step(10) #步长
    while True:
        for i in range(0,50,5):
            p2.step(i) #以步长i增长
            # p2.stop()#停止
            time.sleep(1)
t = threading.Thread(target=_)
t.setDaemon(True)
t.start()
root.mainloop()
Copy after login

Scale

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import threading,time
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
ttk.Scale(
    master=root,
    orient=HORIZONTAL,
    value=75,
    from_=0,
    to=100
).pack(fill=X, pady=5, expand=YES)
ttk.Scale(master=root,orient=HORIZONTAL,bootstyle=WARNING,value=75,from_=100,to=0).pack(fill=X, pady=5, expand=YES)
def scale():
    s2 = ttk.Scale(
        master=root,
        bootstyle=SUCCESS,
        orient=VERTICAL,
        value=0,
        from_=100,
        to=0
    )
    s2.pack(fill=X, pady=5, expand=YES)
    for i in range(101):
        s2.configure(value=i)
        time.sleep(0.1)
        # print(s2.get())
t = threading.Thread(target=scale)
t.setDaemon(True)
t.start()
root.mainloop()
Copy after login

Water ruler

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
fg1 = ttk.Floodgauge(
    master=None,
    cursor=None,
    font=None,
    length=None,
    maximum=100,
    mode=DETERMINATE,
    orient=HORIZONTAL,
    bootstyle=PRIMARY,
    takefocus=False,
    text=None,
    value=0,
    mask=None,
)
fg1.pack(side=ttk.LEFT, padx=5)
fg1.start()
fg2 = ttk.Floodgauge(
    master=root,
    boot,
    font=("微软雅黑",12), #文本字体
    length=100,  #水尺长度
    maximum=10, #增加到10
    mode=INDETERMINATE, #来回不确定
    orient=VERTICAL, #放置垂直方向
    text="文本", #文本
)
fg2.pack(side=ttk.LEFT, padx=5)
fg2.start()
fg3 = ttk.Floodgauge(
    root,
    bootstyle=INFO,
    length=300,
    maximum=200,
    font=("微软雅黑", 18, &#39;bold&#39;),
    mask=&#39;loading...{}%&#39;,
)
fg3.pack(side=ttk.LEFT, padx=5)
fg3.start()
# fg3.stop()
# fg3.configure(mask=&#39;...{}%&#39;)
fg3.configure(value=25) #初始值
fg3.step(50) #将上面25该值增加50步
root.mainloop()
Copy after login

Scroll bar

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window(size=(500,200))
f = ttk.Frame(root).pack(fill=BOTH, expand=YES)
text_content = &#39;&#39;&#39;
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren&#39;t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you&#39;re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it&#39;s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let&#39;s do more of those!
&#39;&#39;&#39;
# t = ttk.Text(f)
# t.insert("0.0",text_content)
# t.place(x=10,y=10,width=480,height=200)
# sl_x = ttk.Scrollbar(t,orient=HORIZONTAL) #使滚动条水平放置
# #放到窗口的底部, 填充X轴竖直方向
# sl_x.pack(side=ttk.BOTTOM, fill=ttk.X)
# sl_y = ttk.Scrollbar(t,boot) #滚动条默认垂直放置
# #放到窗口的右侧, 填充Y轴竖直方向
# sl_y.pack(side=ttk.RIGHT, fill=ttk.Y)
# #两个控件相关联
# sl_x.config(command=t.xview)
# t.config(yscrollcommand=sl_x.set)
# sl_y.config(command=t.yview)
# t.config(yscrollcommand=sl_y.set)

##滚动文本框
from ttkbootstrap.scrolled import ScrolledText
st = ScrolledText(f, padding=5, height=10, autohide=True)
st.pack(fill=BOTH, expand=YES)
st.insert(END, text_content)

root.mainloop()
Copy after login

Message prompt Box

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.dialogs import Messagebox
root = ttk.Window()
print("ok: ",Messagebox.ok(
    message="要在消息框中显示的消息",
    title="消息框的标题",
    alert=False, #指定是否响铃,默认False
))
print("okcancel: ",Messagebox.okcancel(message="确定取消"))
print("retrycancel: ",Messagebox.retrycancel(message="重试取消"))
print("retrycancel: ",Messagebox.show_error(message="显示错误"))
print("retrycancel: ",Messagebox.show_info(message="显示信息"))
print("retrycancel: ",Messagebox.show_question(message="显示问题"))
print("retrycancel: ",Messagebox.show_warning(message="显示警告"))
print("retrycancel: ",Messagebox.yesno(message="是的"))
print("retrycancel: ",Messagebox.yesnocancel(message="是的取消"))
root.mainloop()
Copy after login

Query box

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.dialogs import Querybox
root = ttk.Window()
print("获取日期:",Querybox.get_date())
print("获取float型:",Querybox.get_float(
    prompt="请输入内容:",
    title="获取float型: ",
    initialvalue=666.666, #设置初始值
    # minvalue=None, 
    # maxvalue=None
))
print("获取字体:",Querybox.get_font())
print("获取整数:",Querybox.get_integer())
print("获取字符串:",Querybox.get_string())
root.mainloop()
Copy after login

Subwindow

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
root = ttk.Window()
root.wm_attributes(&#39;-topmost&#39;, 1)#让主窗口置顶
def my():
    ttk.Style("solar")
    #print(ttk.Style().theme_names())#可设置主题风格[&#39;cyborg&#39;, &#39;journal&#39;, &#39;darkly&#39;, &#39;flatly&#39;, &#39;solar&#39;, &#39;minty&#39;, &#39;litera&#39;, &#39;united&#39;, &#39;pulse&#39;, &#39;cosmo&#39;, &#39;lumen&#39;, &#39;yeti&#39;, &#39;superhero&#39;]
    mytoplevel = ttk.Toplevel(root,alpha=0.5)##里面的参数和Window()父窗口一致
ttk.Button(text="my_Toplevel ",command=my).pack()
root.mainloop()
Copy after login

Newly added, I always felt like something was missing before, but I just remembered it today, hahaha! ! !

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.dialogs import Messagebox
root = ttk.Window()
# 在窗口上创建一个菜单栏(最上方的菜单栏横条)
menubar = ttk.Menu(root)
def dianji(): #定义一个点击事件方法
    Messagebox.show_info(title=&#39;走走走!&#39;, message=&#39;该功能还未开放!&#39;)   #消息提示框窗口
# 定义一个竖条
filemenu = ttk.Menu(menubar)
# 在菜单单元中添加一个菜单项File
menubar.add_cascade(label=&#39;设置&#39;, menu=filemenu)
# 在设置菜单项添加命令选项
filemenu.add_command(label=&#39;更多&#39;, command=dianji)
# 添加一条分割线
filemenu.add_separator()
# 定义一个子菜单条
submenu = ttk.Menu(filemenu)  # 和上面定义菜单一样,不过此处是在设置上创建一个空的菜单
submenu.add_command(label="背景")  # 给submenu添加功能选项
submenu.add_command(label="字体")
submenu.add_command(label="大小")
# 添加一个展开下拉菜单,并把上面的子菜单嵌入给它
filemenu.add_cascade(label=&#39;个性化&#39;, menu=submenu, underline=0)
# 同样的在File中加入Exit小菜单,此处对应命令为window.quit
filemenu.add_command(label=&#39;退出&#39;, command=root.quit)
# 在顶部再添加多个菜单项
otherfunction = ttk.Menu(menubar)
menubar.add_cascade(label=&#39;选择&#39;, menu=otherfunction)
menubar.add_cascade(label=&#39;查看&#39;, menu=otherfunction)
otherfunction.add_command(label=&#39;该功能未开放!&#39;)
#帮助
def baidu():
    Messagebox.okcancel(title=&#39;baidu.com&#39;, message=&#39;走走走,自己去百度!&#39;)
help = ttk.Menu(menubar, tearoff=0)
menubar.add_cascade(label=&#39;帮助&#39;, menu=help)
help.add_command(label=&#39;help&#39;, command=baidu)
# 将菜单配置给窗口
root.config(menu=menubar)

root.mainloop()
Copy after login

Panel

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
f = ttk.Frame(root)
f.pack(pady=5, fill=X, side=TOP)
nb = ttk.Notebook(f)
nb.pack(
    side=LEFT,
    padx=(10, 0),
    expand=YES,
    fill=BOTH
)
nb_text = "This is a notebook tab.\nYou can put any widget you want here."
nb.add(ttk.Label(nb, text=nb_text), text="Tab 1", sticky=NW)
nb.add(
    child=ttk.Label(nb, text="notebook tab 2."),
    text="Tab 2",
    sticky=NW
)
f2 = ttk.Frame(nb)
ttk.Button(f2,text="notebook button").pack(side=ttk.LEFT, padx=5, pady=10)
nb.add(f2, text=&#39;Tab 3&#39;)
root.mainloop()
Copy after login

Tree View

How to use ttkbootstrap to create a beautiful interface for Python GUI?

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
root = ttk.Window()
tv = ttk.Treeview(
        master=root,
        columns=[0, 1],
        show=HEADINGS,
        height=5
    )
table_data = [
    (1,&#39;one&#39;),
    (2, &#39;two&#39;),
    (3, &#39;three&#39;),
    (4, &#39;four&#39;),
    (5, &#39;five&#39;)
]
for row in table_data:
    tv.insert(&#39;&#39;, END, values=row)
# print(tv.get_children())#(&#39;I001&#39;, &#39;I002&#39;, &#39;I003&#39;, &#39;I004&#39;, &#39;I005&#39;)
tv.selection_set(&#39;I002&#39;)
tv.heading(0, text=&#39;ID&#39;)
tv.heading(1, text=&#39;NAME&#39;)
tv.column(0, width=60)
tv.column(1, width=300, anchor=CENTER)
tv.pack(side=LEFT, anchor=NE, fill=X)
root.mainloop()
Copy after login

加载gif动图

左边是官网上提供的方法,右边是一个自己定义的方法。

How to use ttkbootstrap to create a beautiful interface for Python GUI?

from pathlib import Path
from itertools import cycle
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from PIL import Image, ImageTk, ImageSequence
class AnimatedGif(ttk.Frame):
    def __init__(self, master):
        super().__init__(master, width=400, height=300)

        # open the GIF and create a cycle iterator
        file_path = Path(__file__).parent / "guanwang.gif"
        with Image.open(file_path) as im:
            # create a sequence
            sequence = ImageSequence.Iterator(im)
            images = [ImageTk.PhotoImage(s) for s in sequence]
            self.image_cycle = cycle(images)

            # length of each frame
            self.framerate = im.info["duration"]

        self.img_container = ttk.Label(self, image=next(self.image_cycle))
        self.img_container.pack(fill="both", expand="yes")
        self.after(self.framerate, self.next_frame)

    def next_frame(self):
        """Update the image for each frame"""
        self.img_container.configure(image=next(self.image_cycle))
        self.after(self.framerate, self.next_frame)

def loadingGif(app):
    numIdx = 12  # gif的帧数
    file_path = Path(__file__).parent / "TestGif.gif"
    frames = [ttk.PhotoImage(file=file_path, format=&#39;gif -index %i&#39; % (i)) for i in range(numIdx)]
    def run(rate):
        frame = frames[rate]
        rate += 1
        gif_label.configure(image=frame)  # 显示当前帧的图片
        gif_label.after(100, run, rate % numIdx)  # 0.1秒(100毫秒)之后继续执行函数(run)
    gif_label = ttk.Label(app)
    gif_label.pack(side=LEFT,padx=20,fill=BOTH, expand=YES)
    run(0)
if __name__ == "__main__":
    app = ttk.Window("Animated GIF", themename="litera")
    gif = AnimatedGif(app)
    gif.pack(side=LEFT,padx=20,fill=BOTH, expand=YES)
    loadingGif(app)
    app.mainloop()
Copy after login

打开本地文件

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from tkinter.filedialog import askopenfilename
root = ttk.Window()
def open_file():
    path = askopenfilename()
    # print(path)
    if not path:
        return
ttk.Button(root, text="打开文件", command=open_file).pack(fill=X, padx=10, pady=10)
root.mainloop()
Copy after login

打开浏览器

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import webbrowser
root = ttk.Window()
def open_url(event):
    webbrowser.open("http://www.baidu.com", new=0)  # 启动web浏览器访问给定的URL
label = ttk.Label(root,text="https://www.baidu.com/",bootstyle=PRIMARY)
label.pack(fill=BOTH)
label.bind("<Button-1>", open_url)
root.mainloop()
Copy after login

The above is the detailed content of How to use ttkbootstrap to create a beautiful interface for Python GUI?. 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.

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.

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.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

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