Tkinter —— 屏蔽按钮问题
要求:当按【苹果】按钮以后,【苹果】就立刻被屏蔽;当按【香蕉】按钮以后,同样也是【香蕉】就立刻被屏蔽。
from tkinter import *
root = Tk()
m=["苹果","香蕉","菠萝"]
def a(i):
Toplevel(root)
b.config(state="disable")
for i in range(len(m)):
b=Button(root,
text=m,
command=lambda i=i : a(i))
b.pack()
mainloop() 你需要在函数中传递按钮 `b` 的引用,这样你就可以在按下按钮时禁用它。可以通过将按钮作为参数传递给函数来实现这个效果。以下是修正后的代码:
from tkinter import *
def disable_button(button):
button.config(state="disable")
def create_buttons(root, labels):
for label in labels:
b = Button(root, text=label, command=lambda btn=b: disable_button(btn))
b.pack()
root = Tk()
button_labels = ["苹果", "香蕉"]
create_buttons(root, button_labels)
root.mainloop()
关键修改在于 `disable_button(button)` 函数中,直接传入按钮的引用,然后在 `create_buttons` 函数中,通过 `lambda btn=b: disable_button(btn)` 将当前按钮传递给函数。这样,当你按下按钮时,它会被禁用。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 from tkinter import *
def disable_button(button):
button.config(state="disable")
def create_buttons(root, labels):
for label in labels:
b = Button(root, text=label, command=lambda btn=b: disable_button(btn))
b.pack()
root = Tk()
button_labels = ["苹果", "香蕉"]
create_buttons(root, button_labels)
root.mainloop() 某一个“天” 发表于 2024-11-18 20:04
按照您给出的程序运行,系统报错! from tkinter import *
root = Tk()
m=["苹果","香蕉","菠萝"]
b=[]
for i in range(len(m)):
bi=Button(root,
text=m,
command=lambda i=i : a(i))
bi.pack()
b.append(bi)
def a(i):
b.config(state="disable")
mainloop()
页:
[1]