[英]Tkinter - Python 3 - Adding an Increment Counter into a class window?
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'”
“ DisplayButton”是我放置的按钮,用于显示值。 仅此而已,但我收到此错误消息。
如果我删除这些类,并仅在单个窗口中运行此代码,则该代码可以正常工作。
任何帮助将非常感激!
如果您的缩进是正确的,那么问题不在于DisplayButton和餐1是全局的,这是因为它们是类级别的,并且您没有以这种方式访问它,这意味着您应该使用self关键字来访问它。 (不必是“ self”-类中任何函数的第一个参数始终定义变量,您可以通过该变量访问同一类中的其他成员-但这是Python风格,使用“ self”。)作为该类中所有函数的参数,例如:
def neg1(self):
然后通过self访问餐1和DisplayButton:
self.meal1 += 1
和:
self.DisplayButton["text"] = str(meal1)
我已经重写了您的课程,以便其他人可以使用self来访问课程中的所有重要内容:
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的任何东西都与在类范围内定义的东西具有相同的可访问性。 我也这样做了,以便您可以使用self.ButtonName来保持对按钮的引用。 最后,我这样做了,以便仅在您正在运行文件并且不将代码导入到另一个文件中时才实例化窗口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.