【问题标题】:how to use a variable with a GUI in python 3如何在 python 3 中使用带有 GUI 的变量
【发布时间】:2013-04-25 17:13:48
【问题描述】:

我正在尝试这样做,所以当您按五次“HELLO”时,文本会变为红色 只是当我添加任何东西到可行时它没有添加任何东西。这是代码。

    from tkinter import *
    class application(Frame):
    global t
  t=1  
   def info(self):
      print ("test")
    global t
    t=t+5

  def createWidgets(self):
    global t
    t=t
    self.exet= Button(self)
    self.exet["text"] = "QUIT"
    self.exet["fg"] = "red"
    self.exet["command"] = self.quit

    self.exet.pack({"side": "left"})

    self.hi = Button(self)
    self.hi["text"] = "HELLO",
    if t == 5:
        self.hi["fg"] = "red"

    self.hi["command"] = self.info
    self.hi.pack({"side": "left"})

  def __init__(self, master=None):
    Frame.__init__(self, master)
    self.pack()
    self.createWidgets()

感谢任何人的帮助!

【问题讨论】:

  • 你的压痕到处都是,你能把它清理干净吗?

标签: python user-interface python-3.x tkinter


【解决方案1】:

这里有几个问题:首先,您使用了一个全局变量,然后将它包含在您的函数范围内。取而代之的是,您应该使用实例变量(self.t,甚至self.counter 以获得更好的可读性)。其次,您正在检查createWidgets 中计数器的值,__init__ 方法仅调用一次。您应该在按钮上的事件处理函数中增加并检查其值。

class application(Frame):

    def info(self):
        self.counter += 1
        print(self.counter)
        if self.counter == 5:
            self.hi["fg"] = "red"

    def createWidgets(self):
        self.counter = 0
        self.exet= Button(self)
        self.exet["text"] = "QUIT"
        self.exet["fg"] = "red"
        self.exet["command"] = self.quit
        self.exet.pack({"side": "left"})

        self.hi = Button(self)
        self.hi["text"] = "HELLO",
        self.hi["command"] = self.info
        self.hi.pack({"side": "left"})

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 2016-09-28
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    相关资源
    最近更新 更多