如何在特定场景Tkinter中清除分配给网格的标签

问题描述 投票:0回答:1

我目前正在使用 python 中的 tkinter 库编写一个漫画阅读器和查看器程序,我正在尝试使其列出当前的标题,当我这样做时,我意识到它与它们重叠,我进行了广泛的搜索但无法找到一个好的程序来让我们在按下新按钮时说“删除/忘记”它们。

我的代码如下:

import json, webbrowser, requests
import tkinter as tk
from tkinter.ttk import *
from urllib import *
import urlopen
from urllib.request import *
import os
os.system("chcp 65001")

app = tk.Tk()

def get_button():
    mid = entry.get()
    if mid == "soap":
        mid = "176758"
    url = f"https://somewebsite/api/gallery/{mid}"
    #label and pack for manga id
    mangaid = tk.Label(text=f"ID : {mid}")
    mangaid.grid(column=0, row=4, columnspan=2,)
    #prints the url
    print(url)
    #open url data
    uf = requests.request(method="get",url=url)
    j_result = uf.json()
    title = j_result['title']
    j_title = title['japanese']
    e_title = title['english']
    #shows the title text
    mangaide = tk.Label(text=f"English Title : {e_title}")
    mangaidj = tk.Label(text=f"Japanese Title : {j_title}")
    mangaide.grid(column=0, row=5, columnspan=2,)
    mangaidj.grid(column=0, row=6, columnspan=2,)

def on_open():
    mid = entry.get()
    if mid == "soap":
        mid = "176758"
    URL = f"https://somewebsite.net/g/{mid}/"
    #opens url
    webbrowser.open(URL, new=2)
    print(URL)
    

enterid = tk.Label(text="Enter ID or Name")
entry = tk.Entry()
button = tk.Button(text="Get", command=get_button)
button2 = tk.Button(text="Open", command=on_open)
enterid.grid(column=0, columnspan=2, pady=(10))
entry.grid(column=0, columnspan=2, padx=(50))
button.grid(row=3, column=0, pady=(10))
button2.grid(row=3,column=1)


app.mainloop()

如果你看第 29-32 行,我会分配一个标签并将其放置在网格上,尽管当我再次按下按钮时,为了获取新数据,它会继续执行以下操作:

第一次数据抓取

第二次数据抓取

在第一个中,您可以看到它工作得很好,但在第二个抓取中,您可以看到它采用了之前的答案并将它们覆盖在后面,所以在要点中,我试图找出解决此问题的方法,我的主要目标是找到一种方法来删除覆盖的文本。

python json tkinter
1个回答
2
投票

app.mainloop()
上方创建空标签,如下所示:

mangaide = tk.Label()
mangaidj = tk.Label()
mangaide.grid(column=0, row=5, columnspan=2,)
mangaidj.grid(column=0, row=6, columnspan=2,)

并使用

get_button()
关键字将文本放在
global
函数内。像这样修改你的
get_button()
函数:

def get_button():
    global mangaidj, mangaide # Using global keyword to access those Labels
    mid = entry.get()
    if mid == "soap":
        mid = "176758"
    url = f"https://somewebsite/api/gallery/{mid}"
    #label and pack for manga id
    mangaid = tk.Label(text=f"ID : {mid}")
    mangaid.grid(column=0, row=4, columnspan=2,)
    #prints the url
    print(url)
    #open url data
    uf = requests.request(method="get",url=url)
    j_result = uf.json()
    title = j_result['title']
    j_title = title['japanese']
    e_title = title['english']
    #shows the title text
    mangaide.config(text=f"English Title : {e_title}") # These lines will
    mangaidj.config(text=f"Japanese Title : {j_title}") # update the text each time

Hpoe 这有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.