我可以通过编程方式随机选择Tkinter Checkbutton吗?

时间:2017-05-15 05:32:50

标签: python random tkinter

免责声明 - 全新的编程,Python(3.x)是我开始选择的语言。

我最近完成了关于codeacademy的Python课程,其中我创建了一个迷你战舰游戏。作为一个学习项目,我正在使用游戏板的Tkinter和Checkbuttons开发GUI,以便它可以在解释器之外播放。

我现在被封锁了,因为我不知道如何让Python随机选择战舰位置的Checkbutton位置 - 并让它在播放器中不可见。

到目前为止我的Tkinter代码......

from tkinter import *

class gui(object):
    def __init__(self):

        master = Tk()
        master.title("Battleships!")

        w = Label(master, text="Let's play Battleships!")
        w.pack()
        w = Label(master, text="Click in a box to try and bomb the 
Battleship:")
        w.pack()

        self.checkvar1 = IntVar()

        c = Checkbutton(master, variable=self.checkvar1, command=self.cb)
        c.pack()

        #Hopefully I can use this to display messages to user as they guess
        w = Label(master, text=" ")
        w.pack()

        Button(master, text="I give up!", command=master.quit).pack()

        master.mainloop()

    def cb(self):
        print("variable is", self.checkvar1.get())
        return self.checkvar1.get()

def main():
    g = gui()

if __name__ == '__main__':
    main()

也许我应该首先创建我的Checkbutton Grid(5 x 5),而不是仅使用一个Checkbutton尝试它(我试图将我的开发切成逻辑问题)?

这是原始游戏代码(无GUI)......

from random import randint

board = []

for x in range(5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print(" ".join(row))

print("Let's play Battleship!")
print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)

for turn in range(4):
    guess_row = int(input("Guess Row (between 0 & 4):"))
    guess_col = int(input("Guess Col (between 0 & 4):"))
    print("Turn", turn + 1)
    if guess_row == ship_row and guess_col == ship_col:
        print("Congratulations! You sunk my battleship!")
        break
    else:
        if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 
4):
            print("Oops, that's not even in the ocean.")
            if turn == 3:
                print("Game Over")
        elif (board[guess_row][guess_col] == "X"):
            print("You guessed that one already.")
            if turn == 3:
                print("Game Over")
        else:
            print("You missed my battleship!")
            board[guess_row][guess_col] = "X"
            if turn == 3:
                print("Game Over")
        print_board(board)

非常感谢任何建议,提示,帮助我学习这个特殊问题的技巧。

1 个答案:

答案 0 :(得分:0)

您可以随时生成所有复选框(在创建时将它们存储在列表中),然后在列表中随机选择项目,存储它,当用户点击时,将他点击的项目与您点击的项目进行比较#39;已存储。