Skip to main content
 首页 » 编程设计

python之ttk.Widget.state() TclError : Invalid state name 错误

2024年10月17日6birdshome

我尝试在 tkinter 中更改 ttk.button 状态(在主循环开始时),就像这样 manual [实现:实际上here .]

import tkinter 
from tkinter import ttk 
 
root = tkinter.Tk() 
 
style = ttk.Style() 
style.map("C.TButton", 
    foreground=[('pressed', 'red'), ('active', 'blue')], 
    background=[('pressed', '!disabled', 'black'), ('active', 'white')] 
    ) 
 
colored_btn = ttk.Button(text="Test", style="C.TButton") 
colored_btn.pack() 
 
colored_btn.state('pressed') 
 
root.mainloop() 

错误结果:

in state return self.tk.splitlist(str(self.tk.call(self._w, "state", statespec))) _tkinter.TclError: Invalid state name p 

请您参考如下方法:

colored_btn.state(('pressed',)) 

来自 Python Documentation :

statespec will usually be a list or a tuple.

我想这个问题来自 8.6 和 8.5 tkinter 版本差异。

请注意,在有问题的手动链接(tkinter 8.5)中有 stateSpac 参数,在 tkinter 8.6 中 - statespec。这样的事情应该总是警告你版本可能会发生变化。