如何使用相同的按钮从 Tkinter Canvas 生成和删除特定的文本标签?

问题描述

我刚开始学习 Tkinter。在完成一个初学者项目时,我遇到了这种情况,我必须使用相同的按钮来生成一个字符串并用新的替换它,因为新的与旧的重叠。以下是代码段:

def ranQ():

    if root.count < len(root.LoQ):
        tx=canv.create_text(400,50,text=root.LoQ[root.count],font=('Jokerman',15),fill="Purple")
        root.count += 1

    else:
        # l2 = Label(root,text="End of 7 questions! Click to generate again!",fg= "white",bg ="red")
        # l2.pack()
        canv.create_text(400,450,10),fill="Purple")
        root.count=0

        random.shuffle(root.LoQ)

# defining background image
im = PhotoImage(file="{path}")

# Creating a canvas

canv = Canvas(root,width =800,height=500)
canv.pack(fill ="both",expand= True)

# Putting the image in canvas

canv.create_image(0,image=im,anchor='nw')

# adding a text label

canv.create_text(400,text ="7 Random Questions!",50),fill="black")
canv.create_text(404,454,fill="purple")

# adding the generate button
btn_g = Button(root,text='Press to generate a random question'.upper(),padx=60,pady=20,fg="white",bg='Red',command=ranQ)
b_window = canv.create_window(220,225,anchor="nw",window= btn_g)

解决方法

你有没有尝试过这样的事情?:

import tkinter as tk
from random import randint

def callback():
    new_text = randint(0,100)
    # Reconfigure the text
    canvas.itemconfig(text_id,text=new_text)

root = tk.Tk()

canvas = tk.Canvas(root,width=200,height=200)
canvas.pack()

# Save the text id that the canvas gives us
text_id = canvas.create_text(100,100,text="")

button = tk.Button(root,text="Click me",command=callback)
button.pack(fill="x")

root.mainloop()

基本上你重新配置文本。您可以找到更多信息here