【问题标题】:Can't update label with a string upon clicking button单击按钮时无法使用字符串更新标签
【发布时间】:2013-07-16 20:23:28
【问题描述】:

尝试进入 Python,我很确定答案就在我面前。但我不太确定如何实施其他人的想法。

我有一个书籍列表,每一个都是一个列表,其中包含标题、所需库存和当前库存的两个翻译。我想弹出一个窗口,然后单击一个按钮,该窗口将显示书籍库存的摘要。 (目前有 4 个。)

我可以让它很好地打印变量,但不知道获取 GUI 消息是怎么回事。另外,当我在两个地方都没有定义 invOutput 时,我会收到错误...这似乎不对。如果它只是在函数内部,它说它没有定义,如果它只是在外面我得到UnboundLocalError: local variable 'invOutput' referenced before assignment

from Tkinter import *

#These are all the books sorted in lists.
books = [ #English Title, Spanish Title, Desired Stock, Current Stock
["Bible", "Biblia", 10, 5],
["Bible Teach", "Bible Teach", 10, 10],
["Song Book", "El Song Book", 10, 10],
["Daniel's Prophecy", "Spanish D Prof", 10, 10]
]

invOutput = ""

def inventoryButton():
        invOutput = ""
        for book in books:
                if book[2] > book[3]:
                    invOutput += "Title: " + book[0] + "\n"
                    invOutput += "You need to order more books.\n\n"
                else:
                    invOutput += "Title: " + book[0] + "\n"
                    invOutput += "Status: Inventory is sufficient.\n\n"
        print invOutput

##############

window = Tk()
window.title("Literature Inventory System")
window.geometry("500x500")

button = Button(window, text="Check Inventory", command=inventoryButton)
button.pack()

summary = Label(window, textvariable=invOutput)
summary.pack()

window.mainloop()


##############

【问题讨论】:

  • 如果其他人的代码让您感到恐慌并且没有帮助,那么任何答案在这里可能有什么好处?你必须先学会读代码,然后才能学会写代码;没有办法。

标签: python user-interface python-2.7 tkinter label


【解决方案1】:

据我了解您的问题,您想获取终端中打印的内容并在 GUI 中显示它吗?如果是这样,这将做到:

from Tkinter import *


books = [
["Bible", "Biblia", 10, 5],
["Bible Teach", "Bible Teach", 10, 10],
["Song Book", "El Song Book", 10, 10],
["Daniel's Prophecy", "Spanish D Prof", 10, 10]
]

def inventoryButton():
    invOutput = ""
    for book in books:
        if book[2] > book[3]:
            invOutput += "Title: " + book[0] + "\n"
            invOutput += "You need to order more books.\n\n"
        else:
            invOutput += "Title: " + book[0] + "\n"
            invOutput += "Status: Inventory is sufficient.\n\n"
    #Set the text of the Label "summary"
    summary["text"] = invOutput

window = Tk()
window.title("Literature Inventory System")
window.geometry("500x500")

button = Button(window, text="Check Inventory", command=inventoryButton)
button.pack()

summary = Label(window)
summary.pack()

window.mainloop()

当您单击“检查库存”时,终端中打印的所有内容现在都显示在 GUI 中。

【讨论】:

  • 这太简单了。
猜你喜欢
  • 1970-01-01
  • 2015-12-20
  • 2013-06-30
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
相关资源
最近更新 更多