【发布时间】:2018-04-10 15:23:03
【问题描述】:
我知道有很多关于如何实现浏览按钮的答案,我使用这些答案创建了以下代码,但是 Pycharm 仍然抛出我不理解的异常,并且 tkinter 代码没有很好的文档记录.
下面是抛出异常的代码:
import os
import fnmatch
from tkinter.filedialog import askopenfilename
from tkinter import *
master = Tk()
master.geometry("550x125+10+10")
filePath = StringVar(None)
def browseFiles():
file = askopenfilename(filetypes = (("text files","*.txt"),("all
files","*.*")), title = "Choose a File.")
filePath.set(file)
for f in file:
E2.insert(1.0, filePath)
return
L1 = Label(master, text = "Client Code:")
L1.place(x=10, y=10)
E1 = Entry(master, width = 20)
E1.place(x=80, y=10)
L2 = Label(master, text = "File Name:")
L2.place(x=10, y=40)
E2 = Entry(master, width = 50, textvariable=filePath)
E2.place(x=80, y=40)
B1 = Button(master, text="Browse", width=10, command=browseFiles)
B1.place(x=425, y=37)
master.mainloop()
例外情况如下:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\klighthouse\AppData\Local\Programs\Python\Python36-
32\Lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/klighthouse/PycharmProjects/untitled/Run_EPC.py", line 58,
in browseFiles
E2.insert(1.0, filePath)
File "C:\Users\klighthouse\AppData\Local\Programs\Python\Python36-
32\Lib\tkinter\__init__.py", line 2686, in insert
self.tk.call(self._w, 'insert', index, string)
_tkinter.TclError: bad entry index "1.0"
代码将运行,程序运行,但我认为异常会减慢它的速度,所以我很想以某种方式摆脱它们。任何帮助表示赞赏。
【问题讨论】:
-
您可以尝试使用整数 (1) 而不是 1.0 吗?可能会抛出异常
-
错误告诉你究竟出了什么问题。您不能使用浮点数作为条目小部件的索引。
-
将其更改为仅一个确实会使异常消失,但除了文件路径之外,它还会在输入框中添加“PY_VAR0”。我该如何摆脱它?