python - 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)
谢谢,希望它足够清楚。
解决方案
由于有多个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()
如果可以,请使用。
推荐阅读
- python - AttributeError:模块“lightgbm”没有属性“数据集”
- javascript - WKWebView 在脚本加载之前不加载 HTML 内容
- python - 如何从文件夹中随机选择一个文件而不将所有文件读入内存
- javascript - 在类方法中访问对象属性
- php - woocommerce 的 Wordpress 重定向错误
- ruby - 像 PHP 中的内联 RubyDocumentor 行?
- android - 如何使用 rxJava 收集表单输入、评估和有条件地转到另一个视图或发布数据
- python-3.x - 递归函数不更新python中的列表
- javascript - 不需要的 React 组件重新渲染?
- java - 将对象从一个活动传递到另一个活动以更改其值