gpt4 book ai didi

python - (Python) 通过单选按钮 python 更新背景

转载 作者:行者123 更新时间:2023-12-01 02:34:41 28 4
gpt4 key购买 nike

所以我试图在选择某个单选按钮时更改此框架的背景。

我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。)

问题是每当我选择单选按钮时都会出现以下错误:

configure() missing 1 required positional argument: 'self'

但是,当将 self 放入内部或 configure 时,它会说 self 未定义。

我并不是 100% 知道何时使用 self,因此我们将不胜感激。

改变背景的函数:

def bgLight():
Options.configure(self, bg="#fff")
Options.configure(self, fg="#000")

def bgDark():
Options.configure(bg="#000")
Options.configure(fg="#fff")

以及单选按钮的代码:

class Options(tk.Frame):

def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller

label = tk.Label(self, text="Options", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
label = tk.Label(self, text="Change it up a bit!", font=SUBTITLE_FONT)
label.pack(fill="x", pady=10)

#These are the two radio buttons that will change the background color
radio = tk.Radiobutton(self, text="One", value=1, command=bgLight)
radio.pack()
radio = tk.Radiobutton(self, text="Two", value=0, command=bgDark)
radio.pack()

button = tk.Button(self, text="Back To Main Menu",
command=lambda: controller.show_frame("Menu"))
button.pack()

就像我说的,我对何时何地使用 self 没有 100% 的信心,所以我主要是在尝试将它放在哪里。

最佳答案

方法configure需要应用于实例,而不是基类。

要使其在 Options 类级别工作,您可以将函数 bgLightbgDark 声明为该类的方法:

def bgLight(self):
self.configure(bg="#fff")
#self.configure(fg="#000") no foreground on Frame

def bgDark(self):
self.configure(bg="#000")
#self.configure(fg="#fff")

不要忘记更改 Radiobutton 命令中的调用:

radio = tk.Radiobutton(self, text="One", value=1, command=self.bgLight)
radio = tk.Radiobutton(self, text="Two", value=0, command=self.bgDark)
<小时/>

在应用程序级别处理此问题的一种方法是在 controler 中定义属性 backgroundforeground ,然后调用该方法当您需要时,通过从controler提供参数来配置。请注意,某些小部件没有前景属性,例如 tkinter.Frame

选项中,方法可以是:

def bgLight(self):
self.controller.background = "#fff"
self.controller.foreground = "#000"

def bgDark(self):
self.controller.background = "#000"
self.controller.foreground = "#fff"

关于python - (Python) 通过单选按钮 python 更新背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46382039/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com