![](/img/trans.png)
[英]How do i use a variable that is defined inside of a function, outside of a function?
[英]How Do I return a variable that is changed within a function inside a class and use it in a function outside of the class
我正在尝试使用按钮(tkinter)尝试更改游戏的难度。 当我单击“简单”,“中等”或“困难”按钮时,应将整体难度分别更改为每个难度12,16,20的对应值。 但是,当我尝试在课堂外使用更改后的难度值时,出现错误:screen.ontimer(play,1000 //难度)NameError:未定义名称“ difficulty”
我试图返回self.difficulty,但是我不确定该怎么做。
class Application(Frame):
def __init__(self, master):
super().__init__(master)
self.difficulty = -1
self.grid()
self.login = self.create_main()
self.read = None
def changeVariable1(self):
self.difficulty = 12
def changeVariable2(self):
self.difficulty = 16
def changeVariable3(self):
self.difficulty = 20
def diff(self):
global radius
if self.difficulty == 12:
radius = (30)
elif self.difficulty == 16:
radius = (20)
elif self.difficulty == 20:
radius = (10)
def create_read(self):
read = Toplevel()
Button(read, text="Easy", font='Helvetica 10 bold', command=self.changeVariable1).grid(row=3, column=2)
Button(read, text="Medium", font='Helvetica 10 bold', command=self.changeVariable2).grid(row=3, column=3)
Button(read, text="Hard", font='Helvetica 10 bold', command=self.changeVariable3).grid(row=3, column=4)
return read
def play(app):
rgb = (random(), random(), random())
timeTaken = time() - startTime
circles.append(my_circle(rgb))
screen.title('SCORE: {}, TIME LEFT: {}'.format(score, int(round(gameLength - timeTaken, 0))))
if time() - startTime > gameLength:
screen.title('FINAL SCORE: {}'.format(score))
screen.onclick(None)
screen.clear()
else:
screen.ontimer(play, 1000 // app.difficulty)
root = Tk()
app = Application(root)
root.mainloop()
play(app)
我希望(通过按钮)选定的难度值将在功能play()中使用。
您的函数在类之外,因此,如果要使用该类的任何成员,则应将类的对象作为外部函数中的参数传递,并抛出该对象,您可以使用该类的成员。
因此,请检查下面给出的更新代码。
def play(app):
rgb = (random(), random(), random())
timeTaken = time() - startTime
circles.append(my_circle(rgb))
screen.title('SCORE: {}, TIME LEFT: {}'.format(score, int(round(gameLength - timeTaken, 0))))
if time() - startTime > gameLength:
screen.title('FINAL SCORE: {}'.format(score))
screen.onclick(None)
screen.clear()
else:
screen.ontimer(play, 1000 // app.difficulty)
root = Tk()
app = Application(root)
root.mainloop()
play(app)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.