Python tkinter 按钮文本未出现

时间:2021-07-18 14:07:23

标签: python tkinter

我正在 Python tkinter 中制作井字游戏。每次我尝试在 click 函数中配置按钮的文本时,文本都不会出现。奇怪的是,当我输入:print(buttons_list[c][d].cget("text")) 配置按钮后,它会打印我设置的文本,但文本本身并没有出现在按钮上。有人可以帮我解决这个问题吗? 到目前为止我的代码(未完成):

from tkinter import *

screen = Tk()
screen.title("Tic Tac Toe")
screen.geometry("600x600+350+10")
buttons_list = []
clicked = []
turns = 0


def click(c, d):
    global turns
    turns += 1

    if turns % 2 == 0:
        buttons_list[c][d].configure(text="X", fg="red")
    else:
        buttons_list[c][d].configure(text="O", fg="green")


x = -200
y = 0
for i in range(3):
    buttons_list.append([])
    for j in range(3):
        b = Button(screen, height=100, width=200, bg="papaya whip", command=lambda i=i, j=j: click(i, j))
        x += 200
        b.place(x=x, y=y)
        buttons_list[i].append(b)
    y += 200
    x = -200


screen.mainloop()

非常感谢 TheLizzard 帮助我!更新代码:

from tkinter import *

screen = Tk()
screen.title("Tic Tac Toe")
screen.geometry("600x600+350+10")
turns = 0


def click(c, d):
    global turns
    turns += 1

    if turns % 2 == 0:
        buttons_list[c][d].configure(text="X", fg="red", font=("Arial", 50))
    else:
        buttons_list[c][d].configure(text="O", fg="green", font=("Arial", 50))


pixel = PhotoImage(width=1, height=1)
buttons_list = []

for i in range(3):
    row = []
    for j in range(3):
        button = Button(screen, height=200, width=200, image=pixel, text=" ", compound="c", bg="papaya whip",
                        command=lambda i=i, j=j: click(i, j))
        button.grid(row=i, column=j)
        row.append(button)
    buttons_list.append(row)

screen.mainloop()

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

from tkinter import *

screen = Tk()
screen.title("Tic Tac Toe")
screen.geometry("600x600+350+10")
turns = 0


def click(c, d):
    global turns
    turns += 1

    has_been_clicked = (buttons_list[c][d].cget("text") != " ")
    print(has_been_clicked)

    if turns % 2 == 0:
        buttons_list[c][d].configure(text="X", fg="red")
    else:
        buttons_list[c][d].configure(text="O", fg="green")


pixel = PhotoImage(width=1, height=1)
buttons_list = []

for i in range(3):
    row = []
    for j in range(3):
        button = Button(screen, height=200, width=200, image=pixel, text=" ", compound="c", bg="papaya whip", command=lambda i=i, j=j: click(i, j))
        button.grid(row=i, column=j)
        row.append(button)
    buttons_list.append(row)

screen.mainloop()

我使用 this 方法强制按钮的大小以像素而不是字符为单位。我还使用 .grid 将按钮放在网格中。我还在函数中添加了一个 has_been_clicked 变量,这样您就可以更轻松地实现程序的其余部分。

相关问题