我正在制作一个Rush-Hour游戏。我正在建立一个gui来展示我找到的解决方案。 我建立了一个保持当前状态的表。现在我想将电路板更新到下一个状态。如何刷新GUI?
import Tkinter as tk
dict = {'X':'red', 'A': 'cyan', 'B': 'dark green', 'C': 'gold', 'D': 'green2', 'E': 'tan1', 'F': 'deep pink', 'G': 'bisque2', 'H': 'navy', 'I': 'orange', 'J': 'khaki1', 'K': 'purple1', 'O': 'Lightblue3', 'P': 'salmon', 'Q': 'lemon chiffon', 'R': 'OliveDrab2'};
class ExampleApp(tk.Tk):
def __init__(self, board):
tk.Tk.__init__(self)
t = SimpleTable(self, board, 8, 8)
t.pack(side="top", fill="x")
t.set(7,7,"2")
class SimpleTable(tk.Frame):
def __init__(self, parent, board, rows=8, columns=8):
# use black background so it "peeks through" to
# form grid lines
tk.Frame.__init__(self, parent, background="black")
self._widgets = []
for i in range(rows):
current_row = []
for j in range(columns):
if (i >= 1 and i <=6 and j >= 1 and j <=6):
vehicleId = board[i-1][j-1]
if (vehicleId != ' '):
label = tk.Label(self, text=vehicleId, bg=dict[vehicleId], borderwidth=0, width=10)
else:
label = tk.Label(self, text=vehicleId, bg='gray75', borderwidth=0, width=10)
elif (i == 3 and j == 7):
label = tk.Label(self, text="exit", bg='gray30', borderwidth=0, width=10)
else:
label = tk.Label(self, text="", bg='gray60',
borderwidth=0, width=10)
label.grid(row=i, column=j, sticky="nsew", padx=2, pady=2)
current_row.append(label)
self._widgets.append(current_row)
for j in range(columns):
self.grid_columnconfigure(j, weight=1)
def set(self, row, column, value):
widget = self._widgets[row][column]
widget.configure(text=value)
if __name__ == "__main__":
# initial state
board = [['O', ' ', ' ', ' ', ' ', ' '], ['O', ' ', ' ', ' ', ' ', ' '], ['O', 'X', 'X',' ', ' ', ' '], ['P', ' ', 'A', 'Q', 'Q', 'Q'], ['P', ' ', 'A', ' ', ' ', 'B'],['P', ' ', 'R', 'R', 'R', 'B']]
# second state
board2 = [['O', ' ', ' ', ' ', ' ', ' '], ['O', ' ', ' ', ' ', ' ', ' '], ['O', ' ', 'X','X', ' ', ' '], ['P', ' ', 'A', 'Q', 'Q', 'Q'], ['P', ' ', 'A', ' ', ' ', 'B'],['P', ' ', 'R', 'R', 'R', 'B']]
app = ExampleApp(board)
app.mainloop()
答案 0 :(得分:0)
您必须保留对小部件的引用,稍后您可以使用它来更改文本。例如,您可以保留每行的标签列表:
labels = []
for i in range(rows):
labels.append([])
for j in range(columns):
...
label = Label(...)
labels[-1].append(label)
...
要修改文本,请使用标签的config
方法:
for i in range(rows):
for j in range(columns):
labels[i][j].config(text="this is new text")