2016-06-06 2 views
0

Я пытаюсь создать простую игру. В настоящее время я создаю страницу настроек, однако, когда я пытаюсь вернуться на главный экран, этого не происходит. Не могли бы вы помочь мне найти мою ошибку. Также я пытаюсь сохранить каждый экран в функции, а в моем цикле while я пытаюсь перейти на разные страницы.Переключение окон в Tkinter

import tkinter as tk 
win = tk.Tk() 
win_state = False 
font = "" 


world=[ [0,0,0,1], 
     [0,0,0,0], 
     [0,0,0,0], 
     [2,0,0,0]] 

def key(event): 
    global pressed 
    pressed = event.keysym 

pressed = "" 
screenMode = 0 

def deleteallitems(): 
    for child in win.winfo_children(): 
     child.destroy() 
def drawgrid(): 
    global win 
    global win_state 
    global canvas 
    win.geometry("400x600") 
    canvas = tk.Canvas(win, width = 410, height = 500) 
    canvas.pack() 
    for x in range(4):#ys 
     for y in range(4):#xs 
      canvas.create_rectangle(x*100+5,y*100+5,x*100+100+5,y*100+100+5) 
      if(world[x][y]==1): 
       canvas.create_oval(x*100+5,y*100+5,x*100+100+5,y*100+100+5,fill="Blue") 
      elif(world[x][y]==2): 
       canvas.create_rectangle(x*100+5+15,y*100+5+10,x*100+5+20,y*100+100+5-10,fill="green") 
       canvas.create_rectangle(x*100+5+15,y*100+5+10,x*100+100+5-15,y*100+100+5-50,fill="green") 
    win.bind("<Key>", key) 
    button = tk.Button(win, text = "Click Me!", command= moveCharacter)  
    button.pack() 
def moveCharacter(): 
    global pressed 
    global win_state 
    global win 
    global world 
    pressed = "none" 
    while (pressed == 'none'): 
     win.update() 
    print("Keyed!!") 
    print (pressed) 
    breakloop = False 
    for y in range(4): 
     for x in range(4): 
      if(world[y][x] == 1): 
       world[y][x] = 0 
       print("Found!!") 
       try: 
        if(pressed=="Up"): 
         if(world[y][x - 1] == 2): 
          win_state = True 
          goToWinScreen() 
         world[y][x - 1]=1 
        if(pressed=="Down"): 
         if(world[y][x + 1]==2): 
          win_state = True 
          goToWinScreen() 
         world[y][x + 1]=1 
        if(pressed=="Right"): 
         if(world[y - 1][x]==2): 
          win_state = True 
          goToWinScreen() 
         world[y - 1][x]=1 
        if(pressed=="Left"): 
         if(world[y - 1][x]==2): 
          win_state = True 
          goToWinScreen() 
         world[y - 1][x]=1 
       except: 
        world[y][x]=1 

        breakloop=True 
        break 
      if(breakloop): 
       break 
    win.update() 
def Draw(): 
    drawgrid() 
    deleteallitems() 
def goToWinScreen(): 
    global screenMode 
    screenMode = 2 
def winScreen(): 
    can = tk.Canvas(win,width=500,height=500) 
    can.pack() 
    win.resizable(False,False) 
    can.create_text(250,250,text = "You win!", fill = '#55B7FF', font = (font,60)) 
    can.configure(background='#7A5EFF') 

    enterbutton = tk.Button(win, text="Home",command = changeToHome) 
    enterbutton.configure(activebackground = '#7A5EFF', width=10, height=2) 

    can.create_window(410/2,300,anchor = tk.NW, window = enterbutton) 
    win.mainloop() 

def drawStart(): 
    global win 

    win.title("Home Screen") 

    parent = tk.Frame(win) 

    win.resizable(False,False) 
    win.geometry('400x400') 

    title = tk.Label(win, text = "Simple Game", font=(font, 24, 'bold')) 
    title.pack(fill="x", pady = "50") 

    playButton = tk.Button(win, text="Play", width=10, command = changeToPlay) 
    playButton.pack(fill = "y", pady = (0, 50)) 

    settingButton = tk.Button(win, text="Settings", width=10, command = changeToSettings) 
    settingButton.pack(fill = "y") 

    parent.pack(expand=1) 
    win.mainloop() 

def changeToSettings(): 
    global screenMode 
    screenMode = 3 

def changeToPlay(): 
    global screenMode 
    screenMode = 1 

def Settings(): 
    global fontfamily, win 
    win = tk.Tk() 
    win.geometry('400x400') 
    win.title("Settings") 
    fontfamily = tk.StringVar(win) 
    fontfamily.set("Arial") 
    fontFamilyMenu = tk.OptionMenu(win, fontfamily, "Arial", "Courier New", "Comic Sans MS", "Fixedsys", "MS Sans Serif", "MS Serif", "Symbol", "System", "Verdana") 
    fontFamilyMenu.pack(pady = (25, 300)) 
    home = tk.Button(win,text="Home",command = changeToHome) 
    home.pack() 
    win.mainloop() 
def changeToHome(): 
    global screenMode 
    global font 
    font = fontfamily.get() 
    screenMode = 0 

while 1: 
    if(screenMode == 0): 
     drawStart() 
    if(screenMode == 1): 
     Draw() 
    if(screenMode == 2): 
     winScreen() 
    if(screenMode == 3): 
     Settings() 
    win.update() 
+0

Какая ваша ошибка? – ppperry

+0

Нет ошибки, это просто ничего не делает –

+1

Запустили ли вы ее через отладчик? Вы также можете попытаться упростить его - попросите его сделать гораздо меньше, пока вы не найдете, где это не удается, а затем создайте оттуда. – CindyH

ответ

1

Как насчет того, чтобы попытаться не использовать этот цикл? Я изменил ваш код, но его далекий от совершенства:

import tkinter as tk 

"""I am going to make a game to use arrow keys to move a character to a flag""" 

font, win = "", ''  # Define win so you can use 'global' or you cna pass it by argument 

world=[ [0,0,0,2], 
     [0,0,0,0], 
     [0,0,0,0], 
     [1,0,0,0]] 


def drawgrid(): 
    global win 
    canvas = tk.Canvas(win, width = 400, height = 400) 
    for x in range(4):#ys 
     for y in range(4):#xs 
      canvas.create_rectangle(x*100+5,y*100+5,x*100+100+5,y*100+100+5) 
      if(world[x][y]==1): 
       canvas.create_oval(x*100+5,y*100+5,x*100+100+5,y*100+100+5,fill="Blue") 
      elif(world[x][y]==2): 
       canvas.create_rectangle(x*100+5+15,y*100+5+10,x*100+5+20,y*100+100+5-10,fill="green") 
       canvas.create_rectangle(x*100+5+15,y*100+5+10,x*100+100+5-15,y*100+100+5-50,fill="green") 
def drawStart(): 
    global win 
    win = tk.Tk() 
    win.title("Home Screen") 

    parent = tk.Frame(win) 

    win.resizable(False,False) 
    win.geometry('400x400') 

    title = tk.Label(win, text = "Simple Game", font=(font, 24, 'bold')) 
    title.pack(fill="x", pady = "50") 

    playButton = tk.Button(win, text="Play", width=10) 
    playButton.pack(fill = "y", pady = (0, 50)) 

    settingButton = tk.Button(win, text="Settings", width=10, command = changeToSettings) 
    settingButton.pack(fill = "y") 

    parent.pack(expand=1) 
    win.mainloop() 

def changeToSettings(): 
    win.destroy()   # Destroy win panel 
    Settings()    # Call settings 

def Settings(): 
    global fontfamily, win 
    win = tk.Tk() 
    win.geometry('400x400') 
    win.title("Settings") 
    fontfamily = tk.StringVar(win) 

    fontfamily.set("Arial") 

    fontFamilyMenu = tk.OptionMenu(win, fontfamily, "Arial", "Courier New", "Comic Sans MS", "Fixedsys", "MS Sans Serif", "MS Serif", "Symbol", "System", "Verdana") 
    fontFamilyMenu.pack(pady = (25, 300)) 

    home = tk.Button(win,text="Home",command = changeToHome) 

    home.pack() 

    win.mainloop() 

def changeToHome(): 
    win.destroy()  # Destroy win panel 
    drawStart()   # Call start window 

drawStart() 
+0

Хорошо разработанное приложение tkinter должно создать один экземпляр 'Tk'. Хотя ваш код будет работать в этой конкретной реализации, это не идиоматический способ написать программу tkinter. –

+0

Конечно, но я выиграл, чтобы мои модификации исходного кода были минимальными, чтобы OP мог это понять. –

+0

Мне нужно использовать цикл, чтобы позже я смог удалить все элементы в окне, а затем обновить окно до окончательной версии –

Смежные вопросы