Python Tk - 动态更改按钮,在函数中定义,单击时
我是用 Python 制作 GUI 的新手,我想做的事情应该非常简单。本质上,我有一个对话框类,用于在程序中实例化对话框。该对话框中的其中一件事是我想用它来更改颜色的按钮。我希望用户能够单击按钮,进入颜色选择器,然后返回到对话框,按钮更改为所选的颜色。在我的对话框类中,这是我定义按钮的地方。
def body(self, master):
Label(master, text="Track URL:").grid(row=0)
Label(master, text="Short label:").grid(row=1)
Label(master, text="Long label:").grid(row=2)
b = Button(master, text="Color",bg="white",command=self.chooseColor).grid(row=3)
self.e1 = Entry(master)
self.e2 = Entry(master)
self.e3 = Entry(master)
self.e1.grid(row=0, column=1)
self.e2.grid(row=1, column=1)
self.e3.grid(row=2, column=1)
return self.e1 # initial focus
然后我只想要一个简单的函数来选择颜色
def chooseColor(self):
color = askColor()
b["bg"] = color
我知道 b 现在超出了范围,所以我无法更改它,但我不明白如何在可以更改按钮的地方选择颜色颜色。任何帮助将不胜感激。
I am new to making GUIs with Python and what I am trying to do should be pretty simple. Essentially, I have a dialog class that I use to instantiate a dialog in my program. One of the things on this dialog is a button that I want to use to change color. I want the user to be able to click the button, be taken to a color chooser, then return to the dialog with the button changing to the color that was chosen. In my dialog class, here is where I define the button.
def body(self, master):
Label(master, text="Track URL:").grid(row=0)
Label(master, text="Short label:").grid(row=1)
Label(master, text="Long label:").grid(row=2)
b = Button(master, text="Color",bg="white",command=self.chooseColor).grid(row=3)
self.e1 = Entry(master)
self.e2 = Entry(master)
self.e3 = Entry(master)
self.e1.grid(row=0, column=1)
self.e2.grid(row=1, column=1)
self.e3.grid(row=2, column=1)
return self.e1 # initial focus
Then I just want a simple function to choose the color
def chooseColor(self):
color = askColor()
b["bg"] = color
I understand that b is now out of scope, so I can't change it, but I don't understand how to get the color chosen in a place where I can change the button color. Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
b
设为成员变量:然后
self.chooseColor
可以“看到”self.b
并对其进行更改:Make
b
a member variable:Then
self.chooseColor
can "see"self.b
and make changes to it: