我有剧本
import tkinter as tk
class Btn_maker:
def __init__(self,window):
self.window = window
self.num = 0
self.matrix = [[],[],[]]
def btn_maker(self,cmd,x=1,y=1,padx=5,pady=5):
self.btn = tk.Button(self.window,command = cmd,width = 6,height = 2)
Btn_maker.btn_grid(self,x,y,padx,pady)
def btn_grid(self,x,y,padx,pady):
self.btn.grid(row = x, column = y, padx = padx, pady = pady)
def game_logic(self,x,y):
self.num+=1
if self.num%2==1:
self.btn.config(text = 'X')
else:
self.btn.config(text = 'O')
#self.matrix[x-1][y-1]
window = tk.Tk()
frame1 = tk.Frame(window)
frame1.pack()
label = tk.Label(frame1,text='Game',fg='red',font = 30)
label.pack()
frame2 = tk.Frame(window)
frame2.pack()
btn_instant = Btn_maker(frame2)
btn1 = btn_instant.btn_maker(lambda: btn_instant.game_logic(1,1),x=1,y=1)
btn2 = btn_instant.btn_maker(lambda: btn_instant.game_logic(1,2),x=1,y=2)
btn3 = btn_instant.btn_maker(lambda: btn_instant.game_logic(1,3),x=1,y=3)
btn4 = btn_instant.btn_maker(lambda: btn_instant.game_logic(2,1),x=2,y=1)
btn5 = btn_instant.btn_maker(lambda: btn_instant.game_logic(2,2),x=2,y=2)
btn6 = btn_instant.btn_maker(lambda: btn_instant.game_logic(2,3),x=2,y=3)
btn7 = btn_instant.btn_maker(lambda: btn_instant.game_logic(3,1),x=3,y=1)
btn8 = btn_instant.btn_maker(lambda: btn_instant.game_logic(3,2),x=3,y=2)
btn9 = btn_instant.btn_maker(lambda: btn_instant.game_logic(3,3),x=3,y=3)
window.geometry('200x300')
window.mainloop()
它的工作原理,但当我按下按钮,它改变文本的最后一个按钮,但我需要改变按钮的文本,我按下
It looks like when I run program当我点击第一个按钮enter image description here
2条答案
按热度按时间mjqavswn1#
你没有在btn_maker代码中返回
self.btn
:修复后,您的代码应该可以正常工作
结果:
erhoui1w2#
更新这两个函数,然后尝试