我正在为我的软件工程类构建桌面游戏的GUI。我在Python 2.7(windows)上使用TKinter工具包。我现在被困住,因为我似乎无法找到忽略/忘记按钮的某种顺序的方法。基本上,我正在尝试创建一个代表我的游戏板的按钮网格。现在,我有一个游戏板,在7x7网格上总共有49个按钮。
到目前为止,这是我能够做到的:
我想使用我的按钮对象列表忽略/忘记/删除(缺少更好的描述)某些按钮。我想我可以创建我想要使用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)
答案 0 :(得分: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
位置的顺序(通常第一个索引表示行,第二个索引表示列),但您可以轻松切换它。