首页 > 解决方案 > ttk 样式在函数内部不起作用

问题描述

我有一些 ttk 按钮,但它们在函数内部,每当我尝试对其进行样式设置时,它都不起作用,但是当我创建一个新文件并使用相同的行但没有将其放入函数内部时,它工作得很好。这是代码片段。

def function():
    if Something == Another thing: 
        r = Tk() # Opens new window
        r.title('Lorem ipsum')
        s = ttk.Style()
        s.configure('TButton', font=('Helvetica', 18))
        Button = ttk.Button(r, text = "lorem ipsum dolor sit amet",command = lorem ipsum,style="TButton")
        Label = ttk.Label(r, text = "Get total Stores Values and quantities")
        Label.place(relx = 0.2, rely= 0.4,anchor=CENTER)
        Button.place(relx = 0.5, rely= 0.4 ,width= 500 ,height = 50  ,anchor=CENTER)

谢谢,希望它足够清楚。

标签: pythontkinterttk

解决方案


由于有多个Tk()实例,所以需要指定样式属于哪个实例:

from tkinter import *
from tkinter import ttk

def function():
    if True:
        r = Tk() # Opens new window
        r.geometry('600x400')
        r.title('Lorem ipsum')
        s = ttk.Style(r) # should specify which Tk instance
        s.configure('TButton', font=('Helvetica', 18))
        Button = ttk.Button(r, text="lorem ipsum dolor sit amet", style="TButton")
        Label = ttk.Label(r, text="Get total Stores Values and quantities")
        Label.place(relx=0.5, rely=0.4, anchor=CENTER)
        Button.place(relx=0.5, rely=0.6, width=500, height=50, anchor=CENTER)

root = Tk()
function()
root.mainloop()

请注意,您使用TButton的样式名称会影响所有ttk.Button()(实际上您可以删除style="TButton")。Custom.TButton如果您只想将样式应用于特定的小部件,最好使用其他名称。

避免使用多个Tk()实例。Toplevel()如果可以,请使用。


推荐阅读