【问题标题】:How to use the same button to generate and remove specific text label from Tkinter Canvas?如何使用相同的按钮从 Tkinter Canvas 生成和删除特定的文本标签?
【发布时间】:2021-06-01 18:50:23
【问题描述】:

我刚开始学习 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, text="End of 7 questions! Click to generate again!", font=('Jokerman', 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,0, image=im, anchor='nw')

# adding a text label

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

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

【问题讨论】:

    标签: python tkinter tkinter-canvas


    【解决方案1】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 2021-09-26
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      相关资源
      最近更新 更多