0

我正在为我的软件工程课程构建一个棋盘游戏的 GUI。我在 Python 2.7 (windows) 上使用 TKinter 工具包。我现在被卡住了,因为我似乎无法找到一种方法来忽略/忘记按钮的特定顺序。本质上,我正在尝试创建一个代表我的游戏板的按钮网格。现在,我有一个游戏板,在 7x7 网格上总共有 49 个按钮。

到目前为止,这是我能够做到的:

  1. 实例化列 = x 和行 = y 的所有按钮对象。这很容易建立一个 x*y 的网格
  2. 然后我将每个按钮放入一个列表中(让我们称之为 list1)
  3. 我想使用我的按钮对象列表来忽略/忘记/删除(因为缺乏更好的描述)某些按钮。我在想我可以创建一个我想在其上使用 grid_forget 的按钮对象的索引的第二个列表(list2),然后比较我的两个列表,只保留那些不在 list2 中的列表。不幸的是,这并没有达到我想要的效果。这是代码:

      gameboard = ttk.Labelframe(root, padding = (8,8,8,8), text = "Gameboard", 
                  relief = "sunken")
      #forgetButtons will not be displayed on the game board b/c they do not have a  
      #label (they are not a: room, hallway, starting space)
      forgetButtons = [0,1,3,5,6,7,13,14,16,18,21,30,32,41,42,43,45,46,47,48]
      #this list tracks all the buttons on the gameboard
      myButtons=[]
      count = 0
          for x in range(7): #build a 7x7 grid of buttons (49 buttons total)
              for y in range(7):
                  btn = Button(gameboard, width=7, height=4)
                  myButtons.append(btn)
                  btn.grid(column=x, row=y, padx = 3, pady = 3)
    
                  #do some comparison here between the two lists 
                  #to weed out the buttons found in forgetButtons
    
                  #**or maybe it should not be done here?**
    
                  btn.config(text="Room%d\none\ntwo\nfour\nfive" % x)
    
4

1 回答 1

2

grid_forget如果您不创建它们,则不需要这些小部件。

import itertools
import Tkinter as tk

root = tk.Tk()
forgetButtons = [0,1,3,5,6,7,13,14,16,18,21,30,32,41,42,43,45,46,47,48]
myButtons = []

for x, y in itertools.product(range(7), repeat=2):
    if not x*7 + y in forgetButtons:
        btn = tk.Button(root, width=7, height=4, text="Room%d\none\ntwo\nfour\nfive" % x)
        btn.grid(column=x, row=y, padx=3, pady=3)
        myButtons.append(btn)

root.mainloop()

我不知道计算位置的顺序forgetButtons(通常第一个索引代表行,第二个索引代表列),但您可以轻松切换它。

于 2013-07-31T01:07:31.717 回答