![](/img/trans.png)
[英]How do i use an 'if' on a checkbutton in tkinter. (python 3.8)
[英]How do i access a function from another file in python with Tkinter. I can't find any solution to my specific problem
我是 python 和 Tkinter 的新手,所以我可能在這里犯了一個簡單的錯誤,但這是一個學校項目,因此,我沒有太多時間學習所有內容。 無論如何,我正在使用 Tkinter 制作一個應用程序,我想將代碼拆分為不同的 python 文件,一個文件中的函數並從主文件訪問它們。 3 天以來我一直試圖找出問題所在,這看起來是一個非常簡單的錯誤,但我不知道它是什么。
Tkinter 回調 Traceback(最近一次調用最后一次)中的異常:文件“C:\Users\mcdd1\AppData\Local\Programs\Python\Python39\lib\ tkinter_init _.py”,第 1884 行,調用中返回 self.func( *args) 文件 "d:\mcdd1\Desktop\UNI\Switch-Frames-Template-master\textfunc.py",第 22 行,在 open_file my_text.delete("1.0", END) NameError: name 'my_text' is not定義
這些是我使用過的代碼:主文件是 mainnav.py,
from textfunc import open_file
toolbar_frame = Frame(frame2, bg="blue")
toolbar_frame.pack(fill=X)
my_frame = Frame(frame2)
my_frame.pack(pady=5)
my_text = Text(my_frame, width=97, height=25, font=("Helvetica", 16), selectbackground="yellow", selectforeground="black", undo=True, wrap="none")
my_text.pack()
open_button = Button(toolbar_frame, text="Open", command=open_file)
open_button.grid(row=0, column=0, sticky=W, padx=5, pady=5)
具有函數 textfunc.py 的文件(在同一目錄中)
global open_status_name
open_status_name = False
global selected
selected = False
def open_file():
my_text.delete("1.0", END)
text_file = filedialog.askopenfilename(initialdir="", title="Open File", filetypes=(("Text Files", "*.txt"), ("All Files", "*.*")))
if text_file:
global open_status_name
open_status_name = text_file
text_file = open(text_file, 'r')
stuff = text_file.read()
my_text.insert(END, stuff)
text_file.close()
這些只是我認為解決問題所需的代碼片段。 任何幫助將不勝感激!
my_text變量未在mainnav.py文件中定義。 如果你想訪問它,你可以將它作為參數傳遞給open_file() function:
主導航.py:
from textfunc import open_file
toolbar_frame = Frame(frame2, bg="blue")
toolbar_frame.pack(fill=X)
my_frame = Frame(frame2)
my_frame.pack(pady=5)
my_text = Text(my_frame, width=97, height=25, font=("Helvetica", 16), selectbackground="yellow", selectforeground="black", undo=True, wrap="none")
my_text.pack()
open_button = Button(toolbar_frame, text="Open", command=lambda: open_file(my_text))
open_button.grid(row=0, column=0, sticky=W, padx=5, pady=5)
文本函數.py:
def open_file(my_text):
my_text.delete("1.0", END)
text_file = filedialog.askopenfilename(initialdir="", title="Open File", filetypes=(("Text Files", "*.txt"), ("All Files", "*.*")))
if text_file:
global open_status_name
open_status_name = text_file
text_file = open(text_file, 'r')
stuff = text_file.read()
my_text.insert(END, stuff)
text_file.close()
注意:您需要使用 lambda 將參數傳遞給 Button 的命令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.