python - 我有一个打开网页的脚本,如何通过 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()
解决方案
首先,将内容写入 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)
推荐阅读
- mongodb - Grails MongoDB 插件:v:2 索引键模式中的值不能是 bool 类型
- docker - 将 Dockerfile 指定为管道作业容器
- python - Python tkinter 按钮在 -while 循环条件下不起作用
- python - 使用lmfit python将模型函数参数定义为自变量的函数
- google-cloud-platform - 将数据从变量插入 BQ 表时动态处理 Bigquery 表模式
- oracle - 在 sqlplus 中假脱机时截断行和列
- react-native - 我无法回答原生 iOS 确认 Detox - React native 中的 mocha 应用
- git - git pull 删除了我本地更改的文件而没有冲突
- java - 如何使用java在控制台中打印彩色的xml文件
- html - css:输入按钮标签后面的匹配元素