python - 如何使用相同的按钮从 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, 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)
解决方案
你有没有尝试过这样的事情?:
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()
基本上你重新配置文本。你可以在这里找到更多信息
推荐阅读
- sql-server - 创建一个临时表,显示给定表中所有列的空值百分比
- apache-spark - 如何使用 ConfigMap 将文件加载到容器中的特定路径?
- google-cloud-endpoints - OpenApi 编译随机返回路径为“jsonobject”
- laravel - Laravel 与阿拉伯蛞蝓
- excel - 使用 COUNTIFS 检查字符串和比较值
- vue.js - 如何在 Nuxt 中为特定页面添加外部 js 文件?
- gradle - 将自定义任务集成到多项目构建的生命周期中
- dax - DAX计算列的运行总和
- sql - 错误:用作表达式的子查询返回多行 - POSTGRES
- python - PyQt5 - 多处理时重复的 GUI