Python Tk - 动态更改按钮,在函数中定义,单击时

发布于 2024-12-15 00:15:38 字数 827 浏览 0 评论 0原文

我是用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

歌入人心 2024-12-22 00:15:38

b 设为成员变量:

self.b = Button(.....)

然后 self.chooseColor 可以“看到”self.b 并对其进行更改:

def chooseColor(self):
    color = askColor()
    self.b["bg"] = color # or however you change a color in python/tkinter

Make b a member variable:

self.b = Button(.....)

Then self.chooseColor can "see" self.b and make changes to it:

def chooseColor(self):
    color = askColor()
    self.b["bg"] = color # or however you change a color in python/tkinter
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文