我想重命名部件,如果它显示“Open Space”并在点击时全部禁用按钮。
from tkinter import *
board = Tk()
board.geometry("400x500")
board.title("Board")
b = Button(board, text="Open Space")
b.grid(row=0, column = 1)
c = Button(board, text="Open Space")
c.grid(row=0, column = 2)
d = Button(board, text="Open Space")
d.grid(row=1, column = 0)
e = Button(board, text="Open Space")
e.grid(row=1, column = 1)
f = Button(board, text="Open Space")
f.grid(row=1, column = 2)
g = Button(board, text="Open Space")
g.grid(row=2, column = 0)
h = Button(board, text="Open Space")
h.grid(row=2, column = 1)
i = Button(board, text="Open Space")
i.grid(row=2, column = 2)
board.mainloop()
答案 0 :(得分:0)
通常,您可以使用
将功能分配给Button
Button(..., command=function_name)
但是你需要访问按钮,所以你必须首先创建按钮,然后用参数 - 按钮实例来协助函数 - 这个函数将改变文本并禁用按钮。
b['command'] = lambda:change(b)
# or
b.config(command=lambda:change(b))
import tkinter as tk
# --- function ---
def change(widget):
widget.config(text='o', state='disabled')
#widget['text'] = 'o'
#widget['state'] = 'disabled'
# --- main ---
root = tk.Tk()
a = tk.Button(root, text="Open Space")
a['command'] = lambda:change(a)
a.pack()
b = tk.Button(root, text="Open Space")
b.config(command=lambda:change(b))
b.pack()
root.mainloop()
编辑:
也许您不需要禁用按钮,但您需要删除已分配的功能:
def change(widget):
widget.config(text='o', command=None)
答案 1 :(得分:0)
如果您想更改Button小部件,只需编写想要执行的更改:
btnname.configure(state=tk.DISABLED, text='New Text', command=newcommand)
根据您的情况更改按钮b:
board.b.configure(state=tk.DISABLED, text='New Text', command=newcommand)
您使用state = tk.DISABLED禁用tk.Button并使用state = tk.NORMAL启用它。如果您不想更改命令,请不要包含它。
对于ttk.Button,状态值为state ='disabled'以禁用它,state ='!disabled'再次启用它