【发布时间】:2021-07-18 23:08:29
【问题描述】:
我正在 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()
【问题讨论】:
-
我强烈建议不要在导入某些东西时使用通配符 (
*),你应该导入你需要的东西,例如from module import Class1, func_1, var_2等等或导入整个模块:import module然后你也可以使用别名:import module as md或类似的东西,关键是不要导入所有东西,除非你真的知道你在做什么;名称冲突是问题所在。 -
当您使用
height=100, width=200时,它不是以像素为单位的。它在字符中。尝试将其更改为height=1, width=3。 -
文本出现在按钮上。你的按钮对于屏幕来说太大了。减小按钮的大小,您将看到文本。