不知道是什么原因导致此错误“ AttributeError:'_ io.TextIOWrapper'对象没有属性'tk'”

时间:2019-10-22 19:33:21

标签: python python-3.x tkinter attributeerror

代码不断抛出AttributeError: '_io.TextIOWrapper' object has no attribute 'tk',我不知道是什么原因引起的,我看了其他文章,但没有任何帮助使我对正在发生的事情有所了解。

下面是导致它的代码。

    def showhwk(lesson, popup):
        lesson = lesson.replace("/","")
        popup.withdraw()
        show = Tk()
        show.title("Homework marks for "+lesson)
        show.geometry("+{}+{}".format(positionRight, positionDown))
        try:
            with open(lesson+".csv", "r") as show:
                csvlist = list(csv.reader(show))
            for label in range (len(csvlist)):
                Label(show, text = "hello").grid(row = label)
        except FileNotFoundError:
            show.title("Error!")
            error = Label(show, text = "Homework file was not found")
            error.grid(row = 0)

        def goback3(show):
            popup.deiconify()
            show.withdraw()

        returnbut = Button(show, text = "Return", bg = "#79838e", command = lambda: goback3(show)).grid(row = 40, sticky = W+E)

这是完整的错误:

Traceback (most recent call last):
  File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)

  File "D:\Desktop\Folders\Python\Coursework\coursework code main.py", line 242, in <lambda>

show = Button(popup, text = "Show homework marks", bg = "green", command = lambda: showhwk(lesson, popup))

  File "D:\Desktop\Folders\Python\Coursework\coursework code main.py", line 278, in showhwk

Label(show, text = "hello").grid(row = label)

  File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 3143, in __init__

Widget.__init__(self, master, 'label', cnf, kw)

  File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2561, in __init__

BaseWidget._setup(self, master, cnf)

  File "C:\Users\Olek\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2530, in _setup

self.tk = master.tk

AttributeError: '_io.TextIOWrapper' object has no attribute 'tk'

1 个答案:

答案 0 :(得分:0)

您首先像这样定义show

show = Tk()

稍后,您可以使用以下语句将show重新定义为打开文件句柄:

with open(lesson+".csv", "r") as show:

然后,您尝试在此处使用show作为窗口小部件的母版:

Label(show, text = "hello").grid(row = label)

由于show不再是小部件,因此不能用作其他小部件的母版。这就是为什么出现tkinter错误的原因。