[英]Tkinter - How can I use correctly the "ttk.style()" statement when I have different kind of classes?
In my real code I have a main window where the user can choose to open other kind of windows.在我的真实代码中,我有一个主窗口,用户可以在其中选择打开其他类型的窗口。 In the main one, I defined the ttk
style using the ttk.style()
statement.在主要内容中,我使用ttk.style()
语句定义了ttk
样式。 It works, but if I define the same style in the other classes dedicated for the other windows, the ttk.style()
doesn't work anymore.它有效,但如果我在专用于其他窗口的其他类中定义相同的样式,则ttk.style()
不再起作用。 Why?为什么? Below is an example:下面是一个例子:
from tkinter import *
from tkinter import ttk
class MainWindow:
def __init__(self):
self.parent=Tk()
self.parent.geometry("400x400")
self.parent.title(self.main_name)
self.parent.configure(background="#f0f0f0")
style=ttk.Style()
style.configure("TButton", background="red", padding=0)
MyButton=ttk.Button(self.parent, text="open a new window", command=self.Open)
MyButton.pack()
self.parent.mainloop()
def Open(self):
obj=NewWindow()
class NewWindow():
def __init__(self):
self.parent=Tk()
self.parent.geometry("400x400")
self.parent.configure(background="#f0f0f0")
style=ttk.Style()
style.configure("TButton", background="red", padding=0)
MyButton=ttk.Button(self.parent, text="This button has not a custom style.. why?")
MyButton.pack()
if __name__=="__main__":
app=MainWindow()
Why the window from the NewWindow
class doesn't use the custom ttk
style like the other one from the MainWindow
class?为什么NewWindow
类中的窗口不像MainWindow
类中的另一个那样使用自定义ttk
样式?
Then I want to write just one time the ttk
instructions, because in my real code, all classes use the same style.然后我只想写一次ttk
指令,因为在我的真实代码中,所有类都使用相同的样式。 What is the best way to do it?最好的方法是什么?
Every instance of Tk
is a separate environment, and cannot share data with other instances of Tk
. Tk
每个实例都是一个单独的环境,不能与Tk
其他实例共享数据。 If you want multiple windows to be able to share information with the first window, you must create instances of Toplevel
rather than Tk
.如果您希望多个窗口能够与第一个窗口共享信息,则必须创建Toplevel
而不是Tk
实例。
The reason your second window doesn't accept the new styling is that the Style
object you created belongs to the original root window.您的第二个窗口不接受新样式的原因是您创建的Style
对象属于原始根窗口。 If you want it to affect the new root window you must explicitly tell it so by specifying the master
attribute.如果您希望它影响新的根窗口,您必须通过指定master
属性明确地告诉它。
style=ttk.Style(master=self.parent)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.