【问题标题】:how to remove a button of grid when it is clicked in tkinter在tkinter中单击时如何删除网格按钮
【发布时间】:2021-02-01 11:34:49
【问题描述】:

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

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

不起作用。 它给出了这个错误“TypeError: grid_forget() got an unexpected keyword argument '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", 20), fg="blue")
 shuffle_btn.grid(row=0, column=btn, sticky=N+E+W+S, pady=100)
 root.mainloop()

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

从点击移动后回答单词:(你有书吗?)

【问题讨论】:

  • ans_btn.destroy() 销毁按钮
  • 我认为您的预期输出的图片可能会更好地理解。
  • btn.destroy() 不起作用。

标签: python-3.x tkinter tkinter-button


【解决方案1】:

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

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()

【讨论】:

    猜你喜欢
    • 2023-01-30
    • 2020-08-26
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多