首页 > 解决方案 > 我有一个打开网页的脚本,如何通过 tkinter 使用 Gui 使正文可编辑,本质上是创建一个新网页

问题描述

这是我迄今为止得到的最多的。只需要能够拉起 GUI 来编辑正文。需要创建一个 GUI,我可以拉出一个文本框来编辑正文中的内容。也不确定我是否可以在程序中添加标签。由于我无法在 Html 格式之间插入代码,我将如何调用或仅拉动<h1>标签进行编辑?

import webbrowser
import os
from tkinter import *

f = open("webgen.html", "w")

html_template = """
<html>

<body>

<h1>

Stay tuned for our amazing summer sale!

</h1>

</body>

</html>
"""
#writing code into file
f.write(html_template)
f.close()

filename = 'file:///'+os.getcwd()+'/' + 'webgen.html'
webbrowser.open_new_tab(filename)

window=Tk() #this is the GUI
btn=Button(window, text="To confirm body click here", fg='blue')
btn.place(x=80, y=100)
txtfld=Entry(window, text="", bd=5)
txtfld.place(x=80, y=150)
window.title('Web Generator')
window.geometry("300x200+10+10")
window.mainloop()

标签: pythonhtmluser-interfacetkinter

解决方案


首先,将内容写入 HTML 文件的代码应该在它自己的函数中,它不应该在 .py 代码中松散。首先,该函数应该使用“.get”来获取当前在名为“txtfld”的 Entry 小部件中的文本并将其保存到一个变量中:

text = txtfld.get()

然后,它应该使用“.format”用 HTML 代码创建一个变量,并将“text”变量插入其中:

html_template = """
<html>
<body>
<h1>
{}
</h1>
</body>
</html>
""".format(text)

然后,它应该以写入模式打开 HTML 文件,将“html_template”写入文件,然后关闭它。该函数应该做的最后一件事是在网络浏览器中打开 HTML 文件:

f = open("webgen.html", "w")
#writing code into file
f.write(html_template)
f.close()

filename = 'file:///'+os.getcwd()+'/' + 'webgen.html'
webbrowser.open_new_tab(filename)

假设您将函数命名为“提交”。整个函数应该是这样的:

def Submit():
    text = txtfld.get()
    html_template = """
    <html>
    <body>
    <h1>
    {}
    </h1>
    </body>
    </html>
    """.format(text)
    f = open("webgen.html", "w")
    #writing code into file
    f.write(html_template)
    f.close()
filename = 'file:///'+os.getcwd()+'/' + 'webgen.html'
webbrowser.open_new_tab(filename)

最后,您需要调整 Button 小部件以调用“提交”函数:

btn=Button(window, text="To confirm body click here", fg='blue', command=Submit)

推荐阅读