尝试在python tkinter中更改多个窗口的背景时出现RecursionError

时间:2016-09-25 22:45:17

标签: python tkinter python-3.5

昨晚我开始了一个迷你项目,我希望用tkinter制作一个游戏(而不是pygame,主要是因为我不知道如何在{{1}制作多个窗口}})。

我希望用户猜测RGB值并计算其准确度。然而,每当我运行我的代码时,我在pygame函数期间得到RecursionError并且没有颜色发生变化。我很困惑为什么。

startgame

我在from tkinter import * import random class multiWindow(Tk): def __init__(self): # ******* CREATE WINDOWS ******* window1 = Tk() window2 = Tk() window3 = Tk() # ******* WINDOW DIMENSIONS ******* windowH = 100 windowW = 250 # ******* SCREEN RES ******* screenW = 1366-windowW screenH = 768-windowH # ******* COORDINATES OF WINDOWS ******* window1.geometry('%dx%d+%d+%d' % (windowW,windowH,screenW/6,screenH/3)) window2.geometry('%dx%d+%d+%d' % (windowW,windowH,screenW/2,screenH/3)) window3.geometry('%dx%d+%d+%d' % (windowW,windowH,screenW/(6/5),screenH/3)) # ******* WINDOW TITLES ******* window1.title("Color1") window2.title("Color2") window3.title("Color3") # ******** BUTTON START ******* buttonStart = Button(window1,text="Start Game", command=lambda: self.startGame()) buttonStart.pack() # ******* OPEN WINDOWS ******* window1.mainloop() window2.mainloop() window3.mainloop() # ******** PRODUCE RANDOM COLOR ******** def randomRGB(self): return random.randint(0,255) def guessRed(self,window): while True: try: print("I want you to guess the RGB values of the colors in the windows above.") print("Guess the red value of the window displaying ",window) guess = int(input()) if guess < 0 or guess > 255: raise else: return guess break except: print("Error") def startGame(self): # ******** DETERMINE COLOR VALUES ******* colorVal = [0,0,0,0,0,0,0,0,0] for x in range(0,len(colorVal)): colorVal[x] = self.randomRGB() # ******* GIVE WINDOWS COLOR ******* self.window1.configure(background='#%02x%02x%02x'%(colorVal[0],colorVal[1],colorVal[2],)) self.window2.configure(background='#%02x%02x%02x'%(colorVal[3],colorVal[4],colorVal[5],)) self.window3.configure(background='#%02x%02x%02x'%(colorVal[6],colorVal[7],colorVal[8],)) multiWindow = multiWindow() print("This comes after multiwindow class") 中不是很好。刚刚开始阅读它2天前,但我觉得这个问题与我对tkinter的掌握关系不如我对python的掌握。

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

您的程序必须只有Tk的一个实例,您必须只调用mainloop一次。如果您需要其他窗口,请创建Toplevel的实例。如果您有多个Tk实例,那么没有什么能像您期望的那样工作。

您还需要移除guessRed中的无限循环以及对input的调用。 GUI不应该从控制台获取输入。

与其他任何问题无关,您不需要在以下内容中使用lambda

Button(window1,text="Start Game", command=lambda: self.startGame())

在这种情况下,lambda除了使代码稍微复杂之外没有任何其他用途。相反,只需传递对函数的引用:

Button(window1,text="Start Game", command=self.startGame)