如何制作自动填充某些条目的 Tkinter GUI

How can I make a Tkinter GUI that auto fills certain entries

我正在尝试使用 Tkinter 制作一个 GUI,它允许您输入 URL 或 ID。

示例URL:https://www.fanfiction.net/s/10030860/1/The-Final-Battle 示例编号:10030860

如您所见,ID 嵌入在 URL 中。我想要两个条目,一个用于输入 URL,一个用于输入 ID。如果用户填写 URL 框,则会自动生成 ID。 (如果我把示例URL放在URL输入框中,我希望ID框中的示例ID自动生成,反之亦然)如果用户填写ID框,URL自动生成。

更多示例:(括号是假装输入框)

URL: [https://www.fanfiction.net/s/10030860/1/The-Final-Battle] <-- If I fill this in
ID:  [10030860] <-- Python fills this in for me
URL: [https://www.fanfiction.net/s/10030860/1/The-Final-Battle] <-- Python fills this in for me
ID:  [10030860] <-- If I fill this in

到目前为止,这是我的代码:

import tkinter as tk
from tkinter import ttk

# Define a function to autofill in the URL and ID entries
def autofill_id_url():
    fanfic_url.set("https://www.fanfiction.net/s/" + fanfic_id.get() + "/1/")
    root.after(100, autofill_id_url)

# Root window
root = tk.Tk()

# Define the labeled frame where we input stuff
input_frame = tk.LabelFrame(master=root, text="Input")
input_frame.grid(row=0, column=0, padx=1, pady=1, rowspan=2, sticky=tk.NS)

# Label for entering URL
ttk.Label(master=input_frame, text="URL:").grid(row=0, column=0, padx=1, pady=1)
# Entry field for URL
fanfic_url = tk.StringVar()
url_entry = ttk.Entry(master=input_frame, textvariable=fanfic_url)
url_entry.grid(row=0, column=1, padx=1, pady=1)

# Label for entering ID
ttk.Label(master=input_frame, text="ID:").grid(row=1, column=0, padx=1, pady=1)
# Entry field for ID
fanfic_id = tk.StringVar()
id_entry = ttk.Entry(master=input_frame, textvariable=fanfic_id)
id_entry.grid(row=1, column=1, padx=1, pady=1)

# Start callback functions
autofill_id_url()

# Start GUI event loop
root.mainloop()

我有填ID的部分,URL是自动生成的。但是我不知道如何制作当你填写 URL 框时,你会得到为你填写的 ID 框。

提前致谢。

最好在输入框中按下 Enter 键而不是使用 .after().

时自动填充
baseurl = 'https://www.fanfiction.net/s/'

def autofill_url_id(_):
    try:
        # extract the id from the url
        url = fanfic_url.get().strip()
        if url.startswith(baseurl):
            id = url.split('/')[4]
            fanfic_id.set(id)
    except IndexError:
        print('failed to extract id from the url')

def autofill_id_url(_):
    id = fanfic_id.get().strip()
    if id:
        fanfic_url.set(baseurl+id+'/1/')
...
# Start callback functions
#autofill_id_url()
url_entry.bind('<Return>', autofill_url_id)
id_entry.bind('<Return>', autofill_id_url)

您可以使用 StringVartrace_variable 方法进行自动填充。 以下代码将执行此操作,但这只是入门的基本代码,因为它需要更多工作才能完美实现自动填充。

after_ids = {}

def get_url(id_):
    """returns url from id."""
    url = 'https://www.fanfiction.net/s/{}/1/The-Final-Battle'
    return url.format(id_)

def get_id(url):
    """returns id from the url."""
    l = url.split('/')
    return l[4] if len(l) > 4 else ''

def autofill_entry(mode, dalay=1000):
    """Auto-fills Url/ID."""
    for v in after_ids.values():
        root.after_cancel(v)
    if mode == 'url':  
        id_ = get_id(fanfic_url.get())
        after_ids[0] = root.after(dalay, lambda: fanfic_id.set(id_))
    elif mode == 'id':
        url = get_url(fanfic_id.get())
        after_ids[1] = root.after(dalay, lambda: fanfic_url.set(url))

现在将函数 autofill_entry 分配给条目小部件 StringVars。

fanfic_url.trace_variable('w', lambda *a: autofill_entry('url'))
fanfic_id.trace_variable('w', lambda *a: autofill_entry('id'))

此外,我建议您使用 from urllib.parse import urlparse, parse_qs 加入 URL 并从 URL 获取 ID。