繁体   English   中英

Tkinter:使用按钮单击命令获取文本框值并保存为html

[英]Tkinter : Use Button Click command get text box value and save in html

我创建了一个小程序来获取用户输入的文本并将其保存在html文件中。 这是我的小程序示例。

from tkinter import *
from jinja2 import Template

root=Tk()
textBox=Text(root, height=2, width=10)
textBox.pack()
buttonSave=Button(root, height=1, width=10, text="Save",
                command=lambda: createCaseDetails())
buttonSave.pack()

def createCaseDetails():
    # Create The template html for case report
    t = Template("""
            <!DOCTYPE html>
            <html lang="en" >
                <head>
                    <meta charset="UTF-8">
                        <title>Case Report</title>
                </head>
                <body>
                    <h1><span class="blue">&lt;</span>Evidence<span class="blue">&gt;</span> <span class="yellow">System Information</pan></h1>
                    <h2>Created with love by bluebear119 </h2>
                    <h3>Case Description</h3>
                        <p>{{Case_Description}</p>
                </body>
            </html>
            """)

    f = open('Case Report.html', 'w')
    inputvalue = textBox.get("1.0", "end-1c")
    print(inputvalue)
    message = t.render(Case_Description=inputvalue)

f.write(message)
f.close()
print("Case Report.html file saved.")

mainloop()

但是,当我在庞大的代码中实现此功能时,由于该变量来自同一类,但位于另一个函数的变量中,因此无法使用该变量。 我在顶层定义了createCaseDetails()函数,但是我的文本框在另一个函数中,按钮也在另一个函数中。 如何按下按钮并将案例描述文本保存为html。

文本框和按钮将在同一类中定义,如下所示:

Class CreateCaseInterface(Frame):

    def caseInformation(self):
        ...
        Case_Description_text=Text(self.caseInfoFrame,width=30,height=11,yscrollcommand=CaseDescripyscrollbar.set)
        Case_Description_text.grid(row =4, column =1,pady=5)

    def UACaseManagement(self):
        Executebtn = Button(self.UACaseManagementFrame, text="Execute for create and save the case file", command=createCaseDetails(self),width=30,height=5)
        Executebtn.grid(row=12,column= 4,sticky=W,pady=5,columnspan=2)


def createCaseDetails(self):
    ...
    # As I already know declare global is not the solution
    inputvalue = Case_Description_text.get("1.0", "end-1c")
    print(inputvalue)
    message = t.render(Case_Description_text=inputvalue)

错误将是无法在createCaseDetails()函数中使用变量Case_Description_text

巨大文件链接的完整代码: https : //drive.google.com/open? id =1I8TPSPf8XmtaeJ3Vm9Pk0hM1rOgqIcaRMgVUNxyn8ok

您尚未将其分配为类变量,而是已将其分配为该函数范围内的变量,因此当函数结束时,该变量将被销毁。 您需要使用self将其分配给类的属性,即。

def caseInformation(self):
    self.Case_Description_text = ...

def createCaseDetails(self):
    # can then reference it here
    inputvalue = self.Case_Description_text.get()

通常,将tkinter窗口小部件分配给类变量是一个好习惯,这样您就可以从其他位置访问所有窗口小部件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM