【发布时间】:2021-09-16 07:59:17
【问题描述】:
我正在尝试使用 Tkinter 制作一个读取 excel 的 python GUI,然后将 excel 信息上传到数据库中。尝试运行脚本时,我可以上传 Excel 电子表格并阅读它,但是当我单击“提交”按钮时。我得到“运行时错误:在请求上下文之外工作”。错误。有人知道这是如何工作的吗?因为我知道这在 Flask 上是如何工作的,但在 Tkinter 上却不知道。
代码:
root = tk.Tk()
root.geometry("500x500")
#root.pack_propagate(True)
#root.resizable(0, 0)
Label(root, text="Metadata Automation", font=16).place(rely=0, relx=0.10)
frame1 = tk.LabelFrame(root, text="Excel Data")
frame1.place(height=250, width=500)
file_frame = tk.LabelFrame(root, text="Open File")
file_frame.place(height=100, width=400, rely=0.55, relx=0)
button1 = tk.Button(file_frame, text="Browse A File", command=lambda: File_dialog())
button1.place(rely=0.65, relx=0.50)
button2 = tk.Button(file_frame, text="Load File", command=lambda: Load_excel_data())
button2.place(rely=0.65, relx=0.30)
label_file = ttk.Label(file_frame, text="No File Selected")
label_file.place(rely=0, relx=0)
tv1 = ttk.Treeview(frame1)
tv1.place(relheight=1, relwidth=1) # set the height and width of the widget to 100% of its container (frame1).
treescrolly = tk.Scrollbar(frame1, orient="vertical", command=tv1.yview) # command means update the yaxis view of the widget
treescrollx = tk.Scrollbar(frame1, orient="horizontal", command=tv1.xview) # command means update the xaxis view of the widget
tv1.configure(xscrollcommand=treescrollx.set, yscrollcommand=treescrolly.set) # assign the scrollbars to the Treeview Widget
treescrollx.pack(side="bottom", fill="x") # make the scrollbar fill the x axis of the Treeview widget
treescrolly.pack(side="right", fill="y") # make the scrollbar fill the y axis of the Treeview widget
survey = tk.IntVar()
project = tk.IntVar()
#Add checkboxes
SurveyCheckbox = Checkbutton(root, text="Insert a survey", variable=survey, onvalue=1, offvalue=3)
ProjectCheckbox = Checkbutton(root, text="Insert a project", variable=project, onvalue=2, offvalue=4)
SurveyCheckbox.deselect()
ProjectCheckbox.deselect()
#place checkboxes under the excel reader
SurveyCheckbox.place(rely=0.80, relx=0)
ProjectCheckbox.place(rely=0.85, relx=0)
#Add Button
Button(root, text="Submit", command=lambda: Gui(), fg="red").place(rely=0.90, relx=0.1)
def File_dialog():
#This Function will open the file explorer and assign the chosen file path to label_file
filename = filedialog.askopenfilename(initialdir="/",
title="Select A File",
filetype=(("xlsx files", "*.xlsx"),("All Files", "*.*")))
label_file["text"] = filename
return filename
def Load_excel_data():
#If the file selected is valid this will load the file into the Treeview
file_path = label_file["text"]
try:
file = r"{}".format(file_path)
if file[-4:] == ".csv":
df = pd.read_excel(file, skiprows=3, engine='xlrd')
"""clear_data()"""
tv1["column"] = list(df.columns)
tv1["show"] = "headings"
for column in tv1["columns"]:
tv1.heading(column, text=column) # let the column heading = column name
df_rows = df.to_numpy().tolist() # turns the dataframe into a list of lists
for row in df_rows:
tv1.insert("", "end", values=row) # inserts each list into the treeview. For parameters see https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Treeview.insert
else:
df = pd.read_excel(file, skiprows=3, engine='openpyxl')
"""clear_data(tv1)"""
tv1["column"] = list(df.columns)
tv1["show"] = "headings"
for column in tv1["columns"]:
tv1.heading(column, text=column) # let the column heading = column name
df_rows = df.to_numpy().tolist() # turns the dataframe into a list of lists
for row in df_rows:
tv1.insert("", "end", values=row) # inserts each list into the treeview. For parameters see https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Treeview.insert
except ValueError:
tk.messagebox.showerror("Information", "The file you have chosen is invalid")
return None
except FileNotFoundError:
tk.messagebox.showerror("Information", f"No such file as {file_path}")
return None
return df
def clear_data():
tv1.delete(*tv1.get_children())
return None
def Gui():
survey_chk = survey.get()
project_chk = project.get()
utils.ConnectionInit()
df = Load_excel_data()
message = ' '
connection = utils.CreateConnection()
if survey_chk == 1 and project_chk != 2:
utils.CreateSurvey(connection, df)
message = 'hi'
elif project_chk == 2 and survey_chk != 1:
#utils.CreateProject(connection, df)
message = 'chau'
elif survey_chk == 1 and project_chk == 2:
#utils.CreateSurvey(connection, df)
#utils.CreateProject(connection, df)
message = 'hola'
lblMessage.config(text=message)
lblMessage = tk.Label(root)
lblMessage.place(rely=0.90, relx=0.10)
if __name__ == "__main__":
root.mainloop()
错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\SCDBOHU\.conda\envs\Proyecto\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "c:/Users/SCDBOHU/Desktop/GitRepos/SeismicDataAutomation/Project/GUI_TEST.PY", line 68, in <lambda>
Button(root, text="Submit", command=lambda: Gui(), fg="red").place(rely=0.90, relx=0.1)
File "c:/Users/SCDBOHU/Desktop/GitRepos/SeismicDataAutomation/Project/GUI_TEST.PY", line 159, in Gui
utils.CreateSurvey(connection, df)
File "c:\Users\SCDBOHU\Desktop\GitRepos\SeismicDataAutomation\Project\utils.py", line 133, in CreateSurvey
SurveyProjnSelection(connection,crs,tfm,projn_id,survey_list,flag_2d)
File "c:\Users\SCDBOHU\Desktop\GitRepos\SeismicDataAutomation\Project\utils.py", line 168, in SurveyProjnSelection
flash(f"The Geoframe map projection ID {projn_id} you were trying to create with your survey is already created.", 'warning')
File "C:\Users\SCDBOHU\.conda\envs\Proyecto\lib\site-packages\flask\helpers.py", line 421, in flash
flashes = session.get("_flashes", [])
File "C:\Users\SCDBOHU\.conda\envs\Proyecto\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "C:\Users\SCDBOHU\.conda\envs\Proyecto\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object
return self.__local()
File "C:\Users\SCDBOHU\.conda\envs\Proyecto\lib\site-packages\flask\globals.py", line 38, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
【问题讨论】:
-
查看错误回溯。该错误来自您创建的
Project\utils.py文件中的某个位置。看起来问题出在tkinter上。 -
你不能从网络服务器运行 tkinter,如果这是你想要做的。
-
@TheLizzard 你是对的,是我的错,我编码有问题。感谢您的帮助
-
@BryanOakley 并不是我想要做的。谢谢你的回答
标签: python python-3.x user-interface tkinter