python - 如何定义将返回已编辑的全局变量的方法
问题描述
我正在尝试使用 tkinter 使用主菜单编辑我的游戏难度。按下按钮时,简单、中等或困难;目标的半径应该改变大小(更硬=更小)。但是,当我单击按钮时,它不会更改半径,而是将其保留在先前定义的全局变量 20 处。
我尝试通过游戏将 app 作为参数传递。
radius = 20
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()
read.geometry("%dx%d%+d%+d" % (500, 500, 250, 125))
Label(read, text="Menu ", font='Helvetica 10 bold').grid(row=0, column=4)
Label(read, text=" ", font='Helvetica 10 bold').grid(row=1, column=1)
Label(read, text="Difficulty: ", font='Helvetica 10 bold').grid(row=3, column=1)
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)
def play():
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()
score = 0
circles = []
gameLength = 30
screen.onclick(lambda x, y: deletescore())
startTime = time()
play()
screen.mainloop()
我希望当我单击按钮时,它会将半径从 20 更改为其各自的值,easy = 30,med = 20,hard = 10。
解决方案
您的菜单回调调用self.changeVariableX
,但只有那些设置self.difficulty
。永远不会调用基于diff
设置全局的方法。radius
self.difficulty
当试图找出这样的问题时,一个好主意是打印出一些调试信息(使用print
)或使用调试器,它允许您逐步了解按下菜单按钮时发生的情况。
推荐阅读
- ios - 使用字符替换制作有效的 JSON 字符串
- c++ - 在 C++ 中创建自己的错误处理机制
- excel - 在用户桌面上将用户表单另存为 .xlsx
- ios - 使用 Apple 商务管理 (VPP) 可以将我的 APP 分发给不同国家的客户吗?
- numpy - python,numpy 矩阵必须是二维的
- php - 基于父页面动态创建链接(Wordpress)
- asp.net-mvc - 我们可以为 Angular 响应式表单创建模型类(DTO)吗?
- android - service 和 JobService 有什么区别
- android - 如何在自定义日期选择器中禁用某些日子
- c# - 如何调用 IEnumerable
.Any() 方法通过 MethodInfo