如何定义将返回已编辑全局变量的方法

时间:2019-02-12 09:54:53

标签: python tkinter

我正在尝试使用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。

1 个答案:

答案 0 :(得分:1)

您的菜单回调调用self.changeVariableX,但仅设置self.difficulty。永远不会调用基于diff设置全局radius的方法self.difficulty

在尝试找出此类问题时,一个好主意是打印出一些调试信息(使用print)或使用调试器,该调试器允许您逐步了解按下时的情况菜单按钮。