【问题标题】:How do I fix these exceptions for creating a "browse" button function with tkinter in Python?如何修复这些异常以在 Python 中使用 tkinter 创建“浏览”按钮功能?
【发布时间】: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”。我该如何摆脱它?

标签: python button tkinter


【解决方案1】:

E2.insert(1.0, filePath) 传递一个双精度 1.0,但它应该是一个整数。所以E2.insert(1, filePath) 解决了你的问题。

注意:要在开头插入,您应该使用0 而不是1(除非它是空的)

askopenfilename 只允许打开单个文件,因此不需要循环,您可以简单地编写

def browseFiles():
    file = askopenfilename(filetypes = (("text files","*.txt"),("all files","*.*")), title = "Choose a File.")
    E2.insert(0, file)
    return

【讨论】:

  • 如果是空的,我还用1吗?
  • @Kassandstorm 如果你想放在开头,那么我会使用 0,只是为了清楚起见。
  • 感谢您的帮助。不过,它现在正在将“PY_VAR0”添加到文件路径的开头。你知道我应该怎么做吗?
  • @Kassandstorm 和askopenfilename你只能选择1个文件,所以你不需要循环,可以写E2.insert(0, file)
  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2014-09-30
  • 2017-09-16
  • 2019-03-22
  • 2013-02-06
  • 2016-12-22
  • 2020-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多