玩MC的Alex 2025-03-12 17:37 采纳率: 0%
浏览 5

Python Tkinter文本框格式化输入问题


#coding: utf-8
import tkinter as tk
import webbrowser
from tkinter import filedialog

def open_web():
    webbrowser.open("web.html")
def select_file():
    root = tk.Tk()
    root.withdraw()
    file_path = FolderPath=filedialog.askdirectory()
    print({file_path})
    return file_path
def GTI_text_bar():
    return text_bar.get("1.0", "end-1c").encode("utf-8")
def GTI__title_bar():
    return title_bar.get("1.0", "end-1c").encode("utf-8")
def webshow():
    webbrowser.open("savewell.py")

def check_label(text):
    # labels form for <html> @ < /    V1.0
    label = ''
    for i in range(len(text)):
        print(text[i])
    if text[1] == '<':
        for i in range(len(text),1):
            if (text[i] == '/'):
                print(label)
                return label
            label += text[i]

    return "p"



def gen_html():
    content = GTI_text_bar()
    content_title = GTI__title_bar()
#    import Webedit_getfilename
#    file_name = GFW_GTW()
#    file_path = select_file()
    with open("web.html", 'w', encoding='utf-8') as f:
        f.write("""<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>""" + content_title + """</title>
</head>
<body>
""")
#        for i in content.split('\n'):
#            label = check_label(i)
#            f.write(f"    <" + label + ">{i}</" + label + ">\n")
#        f.write("</body>\n</html>")
    list = []
    list_gen_i = ""
    for i in range(len(content)):
        if (content[i] == '\n'):
            list.append(list_gen_i)
            list_gen_i = ""
            i = i + 1
        else:
            list_gen_i += content[i]
    list_length = len(list)
    with open("web.html", 'a', encoding='utf-8') as f:
        for i in range(list_length):
            label = check_label(list[i])
            f.write(f"<{label}>")
            content_write = list[i]
            label_end = 0
            for k in range(len(content_write)):
                if (content_write[i] == "/"):
                    label_end = k
            line_write = ""
            for k in range(len(list[i]) - label_end):
                line_write += list[i][k]
            f.write(f"" + line_write)
            f.write(f"</{label}>")


    open_web()

# 创建主窗口
main = tk.Tk()
main.title('网页编辑器')
main.geometry("1000x500+10+10")


#绝对布局
text_bar = tk.Text(main, width=50, height=10, font=("微软雅黑", 20))
title_bar = tk.Text(main, width=50, height= 1, font=("微软雅黑", 20))

text_bar.place(x=10, y=60)
title_bar.place(x=10, y=10)

gen_button = tk.Button(main, text=f"生成网页文件", width=12, height=2,command=gen_html).place(x=820, y=10)

open_button = tk.Button(main, text=f"打开生成的网页", width=12, height=2,command=open_web).place(x=820, y=50)

# 启动主循环
main.mainloop()

这段代码遇到了编码问题(猜的)
报错是TypeError: can only concatenate str (not "bytes") to str

  • 写回答

4条回答 默认 最新

  • 阿里嘎多学长 2025-03-12 17:50
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    解答

    你遇到了 Tkinter 文本框格式化输入问题。从你的代码中,我可以看到你使用了 Tkinter 创建了一个文本框,但是你想要实现什么样的格式化输入功能?你想要在文本框中输入 URL 并自动将其转换为超链接吗?

    如果是这样,可以使用 Text widget 的 insert 方法来插入超链接。下面是一个简单的示例:

    import tkinter as tk
    
    root = tk.Tk()
    text = tk.Text(root)
    text.pack()
    
    def insert_hyperlink(url):
        text.insert(tk.END, f"<a href='{url}'>{url}</a>")
    
    insert_hyperlink("https://www.example.com")
    root.mainloop()
    

    在上面的代码中,我们使用 insert 方法将超链接插入到文本框中。f"<a href='{url}'>{url}</a>" 是一个格式化的字符串,其中 {url} 将被替换为实际的 URL。

    如果你想要实现更多的格式化输入功能,例如输入日期或时间,可以使用 Text widget 的 insert 方法插入格式化的文本。例如:

    import datetime
    
    def insert_date():
        date = datetime.date.today().strftime("%Y-%m-%d")
        text.insert(tk.END, f"Today's date is: {date}")
    
    insert_date()
    

    在上面的代码中,我们使用 datetime 模块获取当前日期,然后使用 strftime 方法将日期格式化为 "YYYY-MM-DD"。然后,我们使用 insert 方法将格式化的日期插入到文本框中。

    如果你需要更多帮助,请提供更多的信息或代码,我将尽力帮助你解决问题。

    评论

报告相同问题?

问题事件

  • 创建了问题 3月12日