python - _tkinter.TclError:ttk.Frame 的未知选项“-bg”

dap*_*dap 2 python tkinter

我想用 2 个选项卡在我的 GUI 中制作带有颜色的背景,我遇到了这个问题,也许有一些建议?

这是代码:

colors = ["Blue", "Gold", "Red"]

def radCall():
    radSel=radVar.get()
    if radSel == 0: tab1.configure(bg=colors[0])
    elif radSel == 1: tab1.configure(bg=colors[1])
    elif radSel == 2: tab1.configure(bg=colors[2])

radVar = tk.IntVar()
radVar.set(99)

for col in range(3):
    curRad = tk.Radiobutton(mighty, text=colors[col], variable=radVar, 
                            value=col, command=radCall)
    curRad.grid(column=col, row=13, sticky=tk.W)
Run Code Online (Sandbox Code Playgroud)

这是问题所在:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__                           >C:/Users/HP/
    return self.func(*args)                                        top/Kuliah/Se
  File "c:\Users\HP\Desktop\Kuliah\Semester 2\Information TechnologI_jualbeli_Day\Python\week5\Informasi Jual Beli\GUI_jualbeli_Dazan.py", line 277, in radCall
if radSel == 0: tab1.configure(bg=colors[0])
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1646, in configure
return self._configure('configure', cnf, kw)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1636, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))    
_tkinter.TclError: unknown option "-bg"
Run Code Online (Sandbox Code Playgroud)

任何的想法?

Coo*_*oud 5

要玩弄ttk小部件的主题,您应该使用Style,如下所示:

s = ttk.Style()
s.configure('first.TFrame',background='red')
s.configure('second.TFrame',background='green')
s.configure('third.TFrame',background='blue')
Run Code Online (Sandbox Code Playgroud)

那么你的 if 语句将是:

def radCall():
    radSel=radVar.get()
    if radSel == 0: tab1.configure(style='first.TFrame')
    elif radSel == 1: tab1.configure(style='second.TFrame')
    elif radSel == 2: tab1.configure(style='third.TFrame')
Run Code Online (Sandbox Code Playgroud)

同样在您的情况下,您必须colors在顶部定义然后使用colors[0]等等,使用configure().

您也可以尝试只创建一个主题并继续编辑它:

s = ttk.Style()
.... # Rest of code

def radCall():
    radSel=radVar.get()
    if radSel == 0:
        s.configure('custom.TFrame',background=colors[0])
        tab1.configure(style='custom.TFrame')
    elif radSel == 1:
        s.configure('custom.TFrame',background=colors[1])
        tab1.configure(style='custom.TFrame')
    elif radSel == 2:
        s.configure('cusom.TFrame',background=colors[2])
        tab1.configure(style='custom.TFrame')
Run Code Online (Sandbox Code Playgroud)