通过按钮能得到选取的文件名到文本框entry,也能得到文件名,但想直接在文本框中输入然后回车获取文件名却出错
Traceback (most recent call last):
File "C:\Python38\lib\tkinter_init_.py", line 1895, in call
return self.func(*args)
TypeError: select_file_enter() takes 1 positional argument but 2 were given
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.filedialog
import tkinter.simpledialog
import tkinter.messagebox
class Win():
def init(self):
# 实例化窗体
self.root = tk.Tk()
# 窗体尺寸
self.root.geometry('%dx%d' % (650, 300))
# 窗体标题
self.root.title('计算')
# 窗体固定大小
self.root.resizable(False, False)
# 定义变量
inFile = ''
self.var_input_filename = tk.StringVar()
# 绘制窗体
self.body()
def body(self):
# 添加 LabelFrame 输入文件
self.input_frame = ttk.Labelframe(self.root, text='输入文件')
self.input_frame.pack(side='top', fill='x', padx=10, pady=5)
# 向 LabelFrame 添加 Button
self.input_button = ttk.Button(self.input_frame, text='... ...', command=self.select_file)
self.input_button.pack(side='right', padx=5, pady=5)
# 向 LabelFrame 添加 Entry
self.input_entry = ttk.Entry(self.input_frame, textvariable=self.var_input_filename)
self.input_entry.pack(side='right', fill='x', padx=5, pady=5, expand=True)
self.input_entry.bind('<Return>', self.select_file_enter)
def select_file(self):
file_types = [("数据文件", ".dat"), ("文本文件", ".txt"), ("所有文件", "*.*")]
inFile = tk.filedialog.askopenfilename(title='打开文件', filetypes=file_types)
if inFile == "":
tk.messagebox.showinfo(title='提示', message='注意!当前没有打开文件!')
else:
self.input_entry.delete(0)
self.input_entry.insert('end', inFile)
print(inFile)
def select_file_enter(self):
inFile = self.var_input_filename.get()
print(inFile)
if name == "main":
app = Win()
app.root.mainloop()