2

I am programming a simple game using tkinter and want an option at the end to be able to replay the game, but I am not sure how I would go about doing it. I would like to be able to go back to the beginning where i define init. Also is there a way I could do this and not have to quit it so I could save scores as the player keeps playing.

from tkinter import *
import random

class App:
    def __init__(self, master):
        player_dice = []
        for i in range(1,6):
            x = random.randint(1,6)
            player_dice.append(x)
            self.label = Label(master, text = x , fg = "red").grid(row =0, column =i+1)

        self.label = Label(master, text = "Dice:" , fg = "red").grid(row =0, column =1)

        self.hi_one = Button(master, text="one", command= lambda: say_one(player_dice)).grid(row = 1, column = 1)
        self.hi_two = Button(master, text="two", command= lambda: say_two(player_dice)).grid(row = 1, column = 2) 

Here is where I would like to add a button to loop back to init.

def num(var, die, dlist):
    new_window = Toplevel(root)
    if die == 1:
        if guess == total:
            result = Message(new_window, text = "You Win").grid(row = 1, column = 1) 
        else:
            result = Message(new_window, text = "You Lose").grid(row = 1, column = 1)
            restart = Button(new_window, text = "Play Again", command = ?????).grid(row=1, column = 2) 

1 Answer 1

1

Easiest way:

Just add a function resetBoard that resets your game. Obviously there are various parts of the UI that don't need to be re-set, so those can go into __init__, the rest can go into resetBoard() and you can (possibly) call resetBoard() from within __init__.

Correct way:

Implement an MVC or MVP pattern: Separate your data and logic from your UI. Your view (UI) should reflect whatever is in your model, then reseting the game is just a question of reseting the model and firing the correct events so the view is updated (highly simplistic, but the very useful model-view-XXX patterns cannot be properly explained in just a few words.)

1
  • thanks very much. i am just a beginner so I think i will try the easiest way first. I put all I had in init in a function defined resetboard(self) and then in init called self.restboard() but got AttributeError: 'App' object has no attribute 'reset_board' Jul 29, 2013 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.