Tkinter - Python 3 - 将增量计数器添加到类窗口中?
问题描述:
class AppetiserClass():
root = Tk()
root.title("Appetiser Page")
root.geometry("1920x1080")
meal1 = 0
def plus1():
global meal1
meal1 = meal1 + 1
DisplayButton["text"]=str(meal1)
return
def neg1():
global meal1
meal1 = meal1 + 1
DisplayButton["text"]=str(meal1)
return
app = Frame(root)
app.grid()
Label(app, text = "", width = 75, height = 20).grid(row = 1, column = 0, sticky = N)
DisplayButton = Button(app, text = meal1)
DisplayButton.grid(column = 1, row = 2, sticky = W)
DisplayButton.config(height = 10, width = 10)
Plus1Button = Button(app, text = "+1", command=plus1, bg="green")
Plus1Button.grid(column = 2, row = 2, sticky = W)
Plus1Button.config(height = 10, width = 10)
Neg1Button = Button(app, text = "-1", command=neg1, bg="green")
Neg1Button.grid(column = 3, row = 2, sticky = W)
Neg1Button.config(height = 10, width = 10)
root.mainloop()
我遇到的问题是我已经为我的全局变量(meal1,为0)设置了一个值,但是当我按下+1或-1按钮时,值不会显示在“DislpayButton “并且我收到此消息: ”NameError:全局名称'DisplayButton'未定义“Tkinter - Python 3 - 将增量计数器添加到类窗口中?
”DisplayButton“,是我放置的按钮,用于显示值。没有更多,但我收到此错误消息。
如果我删除了类,只需运行该代码,与单一窗口,该代码工作正常。
任何帮助将不胜感激!
答
如果你的缩进是正确的,问题不在于DisplayButton和meal1是全球性的,那就是他们是类级别和你没有访问它的方式,这意味着你应该使用自己的关键字来访问它。 (它没有“自我” - 任何函数的第一个参数的一类总是定义,通过它可以访问其他成员在同一类的变量 - 但它是Python的风格来使用“自我”。)添加自作为参数传递给所有的功能在类,像这样:通过自我
def neg1(self):
,然后访问meal1和DisplayButton:
self.meal1 += 1
和:
self.DisplayButton["text"] = str(meal1)
我已经重新 - 写你的clas这样班上所有重要的东西都可以被其他所有使用自己的东西访问:
from tkinter import *
class AppetiserClass:
meal1 = 0
root = Tk()
app = Frame(self.root)
def __init__(self):
self.root.title("Appetiser Page")
self.root.geometry("1920x1080")
self.app.grid()
Label(self.app, text = "", width = 75, height = 20).grid(row = 1, column = 0, sticky = N)
self.DisplayButton = Button(self.app, text = self.meal1)
self.DisplayButton.grid(column = 1, row = 2, sticky = W)
self.DisplayButton.config(height = 10, width = 10)
self.Plus1Button = Button(self.app, text = "+1", command=self.plus1, bg="green")
self.Plus1Button.grid(column = 2, row = 2, sticky = W)
self.Plus1Button.config(height = 10, width = 10)
self.Neg1Button = Button(self.app, text = "-1", command=self.neg1, bg="green")
self.Neg1Button.grid(column = 3, row = 2, sticky = W)
self.Neg1Button.config(height = 10, width = 10)
self.root.mainloop()
def plus1(self):
self.meal1 += 1
self.DisplayButton["text"]=str(self.meal1)
def neg1(self):
self.meal1 -= 1
self.DisplayButton["text"]=str(self.meal1)
if __name__ == "__main__":
AppetiserClass()
我改变了一个体面的金额。首先,你有很多的任何特殊方法之外编写的代码,这是我喜欢保留除了类变量定义(meal1 = 0等)的类方法中。它是相当随意的 - 任何在方法中定义为self.whatever的东西都与在类作用域中定义的东西具有相同的可访问性。我也做到这一点,以便您可以继续使用self.ButtonName引用您的按钮。最后,我已经这样做了,只有当你运行该文件并且不将你的代码导入到不同的文件时,窗口才被实例化。
@ Pat6089一秒 – furkle 2014-10-31 22:37:42
@ Pat6089我上面更新了 - 一切正常,因为它应该,因此,它是为你的类的作品相互沟通更容易了很多,我做到了。请让我知道,如果你有任何问题。 – furkle 2014-10-31 22:56:29
@ pat6089如果这是有帮助的,请不要忘记使用复选标记选择这个答案。 – furkle 2014-11-01 03:48:44