【问题标题】:Organising code for Tkinter Two-Player GameTkinter 两人游戏的组织代码
【发布时间】:2020-10-18 03:06:06
【问题描述】:

我正在尝试制作一个两人游戏,人们轮流采取行动。我觉得我必须手动更改主窗口才能使两者具有相同的内容和小部件。我如何让自己的事情变得更简单?如何更轻松地在两个窗口之间切换?

from tkinter import *

root = Tk()
root.title('Game')
    
def win1():
    global board
    top2.withdraw()
    top1.deiconify()
    board=top1

def win2():
    top1.withdraw()
    top2.deiconify()
    board=top2
    
top1 = Toplevel()
board = top1
top1.title('Player 1')
top1.withdraw()
buttonp1 = Button(top1, text="Switch to Player 2", command=win2)
buttonp1.grid(row=15, column=0, columnspan=10)


top2 = Toplevel()
board = top2
top2.title('Player 2')
top2.withdraw()
buttonp2 = Button(top2,text="Switch to Player 1", command=win1)
buttonp2.grid(row=15, column=0, columnspan=10)

choice = Button(text="Submit Weapons Choices", command=win1)
choice.grid()
#After this button is pressed, win1 is opened, and the switching from window to window begins.

top_array = [top1, top2]

# When generating the board, I would use "for top in top_array", then run a function which generates widgets. I want the board to start off with the exact same layout.

我遇到的问题是无法在代码中更改文本变量,因为它是在函数中生成的:

top_array = [top1, top2]

def init(board):
    txt = StringVar(board)
    txt.set("\nClick anywhere to begin\n")
    label = Label(board, textvariable=txt)
    label.grid(row = 11, column = 0, columnspan=10)
    
for top in top_array:
    init(top)

【问题讨论】:

    标签: python python-3.x class button tkinter


    【解决方案1】:

    我使用了一个类来使两个窗口以相同的内容开始,但具有不同的标题等,以及一个数组,以便我可以在两者之间切换

    class Player:
        def __init__(self, board, tag, name):
            self.board = board
            self.tag = tag
            self.name = name
    
    p = Player(root,"","")
    board1 = Toplevel()
    board2 = Toplevel()
    gamemode = [Player(board1, "Switch to Player 2", "Player 1"), Player(board2, "Switch to Player 1", "Player 2")]
    
    def switch():
        global pnum
        pnum +=1
        pnum %= 2
        gamemode[pnum].board.withdraw()
        gamemode[((pnum+1)%2)].board.deiconify()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多