所以我现在正在自学python,我正在开发一个简单的GUI菜单。但是我遇到了一个错误,我希望有人能解释,我已经解决了它,我做了self.total_button
按选项,而不是把选项放在括号里(就像我做的按钮上面),但我唯一改变的是,程序运行没有错误。你知道吗
total
方法self.total_button["text"] = "Total £"+ str(self.cash_total)
中的行仅在我以我的方式声明self.total_button
时有效,如果我在括号中声明每个选项,它将声明一个Nonetype' object does not support item assignment
。你知道吗
以后在程序中更新按钮时,布局是否与tkinter中的按钮有关?你知道吗
#Order Up!
#A Simple GUI program, that presents a simple restaurant menu.
#It lists items, and prices.
#Let the user select different items and then show the user the total bill.
from tkinter import *
class Application(Frame):
"""Create a GUI application."""
def __init__(self, master):
"""Initialises the frame"""
super(Application, self).__init__(master)
self.grid()
self.cash_total = 0
self.total_list = []
self.create_widgets()
def create_widgets(self):
"""Creates the widgets that creates the menu ordering systems"""
#Create a instruction label
Label(self,
text = "Click the desired buttons to order something"
).grid(row = 0, column = 0, columnspan = 4, sticky = N)
#Create Burger button
Button(self,
text = "Hamburger no bun",
command = self.hamburger_no_bun
).grid(row = 1, column = 0, sticky = W)
#Creates a total button
#Super weird bug have to set it out like this so i can use the total method later.
self.total_button = Button(self)
self.total_button["text"] = "Total: £"
self.total_button["command"] = self.total
self.total_button.grid(row = 5, column = 5, sticky = W)
#Create Text Box to show current order
self.order_txt = Text (self, width = 100, height = 8, wrap = WORD)
self.order_txt.grid(row = 1, column = 5, sticky = W)
def hamburger_no_bun(self):
"""Creates a hamburger tuple to be added to the list."""
self.hamburger_no_bun = ("Hamburger no bun, £", 2.95)
self.total_list.append(self.hamburger_no_bun)
self.order_txt.insert(0.2, str(self.hamburger_no_bun))
def total(self):
#The affected method
"""Adds the total amount due taken from the total_list"""
for i in self.total_list:
self.cash_total += i[1]
print(self.cash_total)
self.total_button["text"] = "Total £"+ str(self.cash_total)
self.cash_total = 0
#main
root = Tk()
root.title("Order Up! - A Restaurant Menu GUI")
app = Application(root)
root.mainloop()
你可能写了这样的代码
您可能会惊讶地发现
self.total_button
现在拥有值None
。这是因为它保存的是Button
的grid
方法的返回值,而不是按钮引用本身。你知道吗稍后当您尝试使用
self.total_button
时,它将抛出一个异常,因为值是None
,并且None
没有属性"Text"
。你知道吗要解决此问题,必须正确捕获对按钮的引用,并将创建和设置按钮的行拆分为两行。你知道吗
现在您有了对按钮的正确引用,该引用将在
total
方法中稍后使用。你知道吗相关问题 更多 >
编程相关推荐