You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何修改Tkinter应用主题?切换主题无反应该如何解决?

Tkinter ttk主题不生效问题解决

核心原因

你调用的s.theme_use()是ttk.Style类的方法,仅对tkinter.ttk模块下的控件生效,你当前代码里使用的OptionMenu、Button、Label都是tkinter原生控件,不属于ttk控件体系,所以不会响应ttk主题的变更。

解决方法

将所有需要跟随主题变化的控件替换为ttk模块下的对应控件即可,注意ttk控件的样式配置和原生tkinter控件有差异,不要直接给ttk.Button传bg、fg这类原生属性,否则会覆盖主题样式。

修改后可运行代码

from tkinter import *
import tkinter.ttk as ttk

window = Tk()
window.title("Running Python Script") # 创建窗口
window.geometry('550x300') # 窗口尺寸

s=ttk.Style()

list_themes = s.theme_names()
current_theme = s.theme_use()
# 可替换为calm、winnative等你系统支持的主题
s.theme_use('classic')
print(list_themes)

# 补全原代码缺失的owner变量,可根据你的需求修改
owner = ["Spain", "China", "USA", "UK"]

def run():
    if dd_owner.get() == "Spain":
        print("spain")

# 替换为ttk.OptionMenu
dd_owner = StringVar(window)
dd_owner.set(owner[0]) # 默认值
w = ttk.OptionMenu(window, dd_owner, *owner)
w.grid(row=0, column=1)

# 替换为ttk.Button,移除覆盖主题的bg、fg参数,如需自定义颜色可通过ttk.Style配置
run_button = ttk.Button(window, text="Run application {}".format(dd_owner.get()), command=run)
run_button.grid(column=0, row=2)

# 替换为ttk.Label
l1 = ttk.Label(window, text='Select Owner', width=15)
l1.grid(row=0, column=0)

mainloop()

如果需要给ttk控件自定义颜色,可以通过ttk.Style配置样式类后绑定给对应控件,不会影响全局主题的生效。

内容的提问来源于stack exchange,提问作者TangerCity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 09:36:07