Richard21
Richard21

Reputation: 157

AttributeError:'str' object has no attribute 'tk' inside a for loop

I'm making a function open1 in tkinter to read csv files inside a directoy but at the moment to print out the results as labels in my window I'm getting: 'str' object has no attribute 'tk'. I believe the error is in my label(root) but I have tried some other things and has found no answer. I would like to ask for help in this part of my code just as it is and not as a Class.

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()

This is the error:

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'

Upvotes: 2

Views: 248

Answers (1)

Random Davis
Random Davis

Reputation: 6857

You're overwriting your root value in your loop through os.walk:

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

Try calling it something different:

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

Upvotes: 1

Related Questions