python - Tkinter - 当我有不同类型的类时,如何正确使用“ttk.style()”语句?
问题描述
在我的真实代码中,我有一个主窗口,用户可以在其中选择打开其他类型的窗口。在主要的部分中,我使用语句定义了ttk
样式。ttk.style()
它可以工作,但是如果我在其他专用于其他窗口的其他类中定义相同的样式,ttk.style()
则不再起作用。为什么?下面是一个例子:
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()
为什么类中的窗口NewWindow
不像类中的其他窗口那样使用自定义ttk
样式MainWindow
?
然后我想只写一次ttk
指令,因为在我的真实代码中,所有类都使用相同的样式。最好的方法是什么?
解决方案
的每个实例Tk
都是一个单独的环境,并且不能与 的其他实例共享数据Tk
。如果您希望多个窗口能够与第一个窗口共享信息,您必须创建实例Toplevel
而不是Tk
.
您的第二个窗口不接受新样式的原因是Style
您创建的对象属于原始根窗口。如果您希望它影响新的根窗口,您必须通过指定master
属性明确告诉它。
style=ttk.Style(master=self.parent)
推荐阅读
- reactjs - 根据服务器数据反应渲染组件
- visual-studio - SSMS 扩展安装期间出现问题
- wpf - 如果我有来自 LiveCharts 的图表,我无法将元素添加到我的 GUI
- jsf - JSF Bean 在特定方法调用后不运行代码
- java - REST 如何在没有完整实体的情况下发布或放置(@RequestBody)
- python - pymysql - TypeError:字符串格式化期间并非所有参数都转换
- python-3.x - 有没有办法通过在该行的值中提供特定列来访问数据框的任何行?
- julia - 数组中存在的过滤器元素
- react-native - React Native , Redux - TypeError: (0 , _redux.createStore) 不是函数
- python - 不同线程中的输入,不会相互中断