在 tkinter 中单击时如何删除网格按钮

问题描述

我正在尝试将包含几个单词的句子排列到网格按钮上。 当单击该句子的单词时,我想删除网格按钮的单词,然后将其移动到另一行网格按钮。 如何仅删除单击的那个网格按钮? 反复点击,这些文字会移动到其他位置并从网格按钮的原始位置一一消失。

shuffle_btn.grid_forget(row=r,column=c)
shuffle_btn.grid_remove(row=r,column=c)

不起作用。 它给出了这个错误“TypeError:grid_forget()得到了一个意外的关键字参数'row'

我该如何解决这个问题?提前致谢。

代码如下,可以移动,不能删除

from tkinter import *
root = Tk()
root.title('words clicking')
root.geometry("1000x600")
btn_lst = ["Do","you","have","a","book","?"]
w_cnt = 0
# Create answer buttons
def move_to_ans(row,column):
    global cnt,w_cnt
    r = row
    c = column
    if w_cnt < cnt:
        ans_btn = Button(root,text=btn_lst[column],font=(
        "Times",20),fg="black")
        ans_btn.grid(row=1,column=w_cnt,sticky=N+E+W+S,pady=100)
        # shuffle_btn.grid_forget(row=r,column=c)
        w_cnt += 1
 # Create buttons of each word in a sentence
 cnt = len(btn_lst)
 for btn in range(cnt):
     shuffle_btn = Button(root,text=btn_lst[btn],command=lambda row=0,column=btn: move_to_ans(row,column),font=("Times",fg="blue")
 shuffle_btn.grid(row=0,column=btn,pady=100)
 root.mainloop()

预期结果: 点击前洗牌:(有书吗?你)-->点击时如何删除

点击后回答:(你有书吗?)

解决方法

您可以在 root.grid_slaves(row=r,column=c)[0].destroy() 中使用 move_to_ans()

def move_to_ans(row,column):
    global cnt,w_cnt
    r = row
    c = column
    if w_cnt < cnt:
        ans_btn = Button(root,text=btn_lst[column],font=("Times",20),fg="black")
        ans_btn.grid(row=1,column=w_cnt,sticky=N+E+W+S,pady=100)
        root.grid_slaves(row=r,column=c)[0].destroy() # destroy the clicked button
        w_cnt += 1

另一种方法是将按钮实例传递给 move_to_ans()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...