python - AttributeError:'str' 对象在 for 循环中没有属性 'tk'
问题描述
我在 tkinter 中创建了一个函数 open1 来读取目录中的 csv 文件,但目前在我的窗口中将结果打印为标签:'str'对象没有属性'tk'。我相信错误在我的标签(根)中,但我尝试了其他一些方法,但没有找到答案。我想在我的这部分代码中寻求帮助,而不是作为一个类。
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image
from tkinter import filedialog
import os
import glob
import pandas as pd
from pandas import *
root = Tk()
root.title('Results')
root.iconbitmap('aa.ico')
root.geometry("100x150")
def open1():
path = (filedialog.askdirectory())
v1.set(path)
all_files = glob.iglob(os.path.join(path, "*.csv"))
#Read the files in the path
df_from_each_file = [pd.read_csv(f) for f in all_files]
for root, dirs, files in os.walk(path, "."):
for file in files:
a = str(file)
x = re.findall('^([^.]*).*', a)
for i in df_from_each_file:
for n in x:
r = "Result " + n + ": " + str(int(i['Result'].sum()))
#print(results)
label = Label(root, text = r).grid(row=i, column=0, columnspan=2, sticky=W)
v1 = StringVar()
b1 = Button(root, text="File", command=open1)
b1.grid(row=0, column=0, padx=5, pady=2 ,sticky=W)
searchfile1 = Entry(root, textvariable=v1, borderwidth=3)
searchfile1.grid(row=0, column=1, ipadx=140)
root.mainloop()
这是错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "c:python\python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "<ipython-input-38-8acd6f6c673f>", line 33, in open1
labeli = Label(root, text = r)
File "c:python\python37-32\lib\tkinter\__init__.py", line 2766, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "c:python\python37-32\lib\tkinter\__init__.py", line 2292, in __init__
BaseWidget._setup(self, master, cnf)
File "c:python\python37-32\lib\tkinter\__init__.py", line 2262, in _setup
self.tk = master.tk
AttributeError: 'str' object has no attribute 'tk'
解决方案
您正在root
通过以下方式覆盖循环中的值os.walk
:
for root, dirs, files in os.walk(path, "."):
尝试称它为不同的名称:
for root_dir, dirs, files in os.walk(path, "."):
推荐阅读
- pandas - Pandas 删除 NaN 值以及如何在不转换的情况下保留原始数据类型(int)
- html - 如何禁用输入类型=“文件”的文本部分
- javascript - 我想使用带有 chrome 扩展的 querySelector
- laravel - 预定命令更新记录
- python - 将分号分隔的字符串文本文件转换为列并在 Python 中执行排序?
- assembly - 从 NASM 到 MASM
- flutter - Flutter 嵌套小部件 setState 无法按预期工作
- firebase - firebase 在 jenkins 中部署,不知道在哪里使用由 firebase login 创建的令牌:ci
- powerbi - 根据日期切片器更改共享轴/层次结构
- c# - 使用实体框架从 Cosmos Db 获取子文档