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()

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

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

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

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

您还没有将它指定为 class 变量,您已经将它指定为该函数范围内的变量,因此当函数结束时,该变量将被销毁。您需要使用 self 将其分配给 class 的属性,即

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

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

一般来说,将 tkinter 小部件分配给 class 变量是一种很好的做法,这样您的所有小部件都可以从其他地方访问。