首页 > 解决方案 > 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'

标签: pythontkinter

解决方案


您正在root通过以下方式覆盖循环中的值os.walk

for root, dirs, files in os.walk(path, "."):

尝试称它为不同的名称:

for root_dir, dirs, files in os.walk(path, "."):

推荐阅读