[英]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"><</span>Evidence<span class="blue">></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.