简体   繁体   English

如何在tkinter中重启程序

[英]how to restart a program in tkinter

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. 我正在使用tkinter编写一个简单的游戏,希望最后有一个选项可以重玩游戏,但是我不确定如何去做。 I would like to be able to go back to the beginning where i define init. 我希望能够回到定义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. 在这里,我想添加一个按钮以循环回到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) 

Easiest way: 最简单的方法:

Just add a function resetBoard that resets your game. 只需添加一个功能resetBoard重置您的游戏。 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__ . 显然,UI的各个部分不需要resetBoard() ,因此可以进入__init__ ,其余部分可以进入resetBoard()并且您可以(可能resetBoard()__init__调用resetBoard()

Correct way: 正确方法:

Implement an MVC or MVP pattern: Separate your data and logic from your UI. 实施MVC或MVP模式:将数据和逻辑与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.) 您的视图(UI)应该反映出模型中的内容,然后重置游戏只是重置模型并触发正确事件的问题,因此视图得以更新(非常简单,但是非常有用的model-view-XXX模式不能只需几句话就能正确解释。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM