【发布时间】:2019-12-17 17:24:51
【问题描述】:
我在 tkinter 中做了一个井字游戏。
代码如下:
from tkinter import *
index = 0
def play_again():
print("TO DO IMPLEMENT IT!")
def update(button_tekst):
global index
if index % 2 == 0 and button_tekst.get() == "":
button_tekst.set("X")
index += 1
if index % 2 and button_tekst.get() == "":
button_tekst.set("O")
index += 1
def main():
window = Tk()
window.title("Tic tac toe")
window.geometry("400x400")
window.grid_columnconfigure((0,1,2), weight=1)
window.grid_rowconfigure((1, 2, 3), weight=2)
window.grid_rowconfigure(0, weight=1)
again = Button(window, text="Play again", bg="lightskyblue", fg='white', font=30, command=play_again)
again.grid(row=0, columnspan=3, sticky="ewns")
coordinaten = [[1, 0], [1, 1], [1, 2], [2, 0],
[2, 1], [2, 2], [3, 0], [3, 1], [3, 2]]
texten = [StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar()]
for i in range(len(coordinaten)):
button = Button(window, textvariable=texten[i], font=("Helvetica", "30"), command=lambda current_index = i:update(texten[current_index]))
button.grid(row=coordinaten[i][0], column=coordinaten[i][1], sticky="ewns")
window.mainloop()
main()
但是,当我单击按钮时,会显示文本,但按钮会自动调整大小。 我怎样才能防止这种情况? 另外是否需要使用全局索引(或布尔)变量和 7 个 Stringvar 变量?
【问题讨论】: