单击按钮时无法使用字符串更新标签

时间:2013-07-16 20:23:29

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

尝试进入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()


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

1 个答案:

答案 0 :(得分:0)

据我了解你的问题,你想把终端上的内容打印出来并在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中。