You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter如何实现文本框输入内容拼接至URL末尾

Tkinter 实现输入内容拼接固定URL方案

核心获取输入的方法

Tkinter 的单行输入框Entry组件,直接调用.get()方法就能拿到用户输入的字符串内容,直接和固定URL前缀拼接即可完成需求。

原有代码需要修正的问题

  • 补全缺失的导入语句:原代码没有导入Tkinter相关组件和END常量,直接运行会报错
  • 修正输入框字体参数的语法错误:原代码Entry的font参数把字体名和字号包在了同一个引号里,会导致字体设置失效
  • URL拼接直接用f-string格式化,把entry.get()取到的用户输入放到URL末尾即可
  • 输出框的insert方法直接传要插入的字符串,不需要加text=关键字参数
  • 建议对用户输入做首尾去空格处理,避免误输入空格导致生成的链接无效

修正后可直接运行的代码

from tkinter import Tk, Label, Entry, Button, END
import webbrowser

root = Tk()
root.title('Link Opener')
# 本地无对应ico文件时可注释下行避免报错
# root.iconbitmap('images/buh.ico')
root.geometry("512x512")

def openlink():
    # 清空输出框原有内容
    urlink.delete(0, END)
    # 获取输入并去除首尾空白字符
    input_code = entry.get().strip()
    if input_code:
        # 拼接最终链接
        target_url = f"https://www.websitehere.net/{input_code}"
        urlink.insert(END, target_url)
        # 如需生成后自动打开链接,取消下行注释即可
        # webbrowser.open(target_url)

label = Label(root, text="Enter Code", font=("sans", 34))
label.pack(pady=20)

entry = Entry(root, font=("sans", 24))
entry.pack(pady=20)

button = Button(root, text="Open Link", command=openlink, font=("sans", 24))
button.pack(pady=20)

nlink = Label(root, text="Link", font=("sans", 14))
nlink.pack(pady=50)

urlink = Entry(root, font=("Sans", 22), justify=CENTER)
urlink.pack(pady=10)

root.mainloop()

效果说明

运行程序后在输入框填入12345,点击按钮即可在下方输入框生成目标链接https://www.websitehere.net/12345,和预期效果完全匹配。

小提示:如果需要支持输入内容带特殊字符的场景,可以引入标准库urllib.parse的quote方法对输入内容做URL编码,避免特殊字符导致链接无法访问。


内容的提问来源于stack exchange,提问作者Pirgor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 02:21:22