Python tk.Label内部函数失败

时间:2016-02-16 01:28:58

标签: python python-3.x tkinter

我3天前开始学习Python,所以我是新手。 我想要的是选择一个目录并在其中显示图像。 当tk.Label在功能之外时,点击'它工作正常,但在功能内部点击'它抛出:

 Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\*\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1549, in __call__
    return self.func(*args)
  File "C:/Users/*/PycharmProjects/first/app.py", line 90, in click
    tk.Label(gui, image=tk_image).grid(row=1, column=0) # THIS LINE FAILED
  File "C:\Users\*\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 2605, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Users\*\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 2131, in __init__
    BaseWidget._setup(self, master, cnf)
  File "C:\Users\*\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 2109, in _setup
    self.tk = master.tk
AttributeError: 'str' object has no attribute 'tk'

可以请别人解释一下吗?到目前为止,这是我的代码:

import tkinter as tk
from tkinter import Tk
from tkinter import Label
from tkinter import Button
# from tkinter import Image
# from tkinter import PhotoImage # conflict
# from tkinter import Frame
from tkinter import Menu
from tkinter import StringVar
# from tkinter import *
import tkinter.messagebox as mb
import tkinter.filedialog as fd
import getpass
import os
# import fnmatch
from PIL import Image, ImageTk
gui = Tk()
user = getpass.getuser()

gui.title('Project')
gui.configure(background='#4D4D4D') # top level styling
gui.geometry('800x400') # specify root window size and position

def about():
    mb.showinfo("About", "Line\nLine\nLine")

def help_box():
    mb.showinfo("Help", "Sorry, we can\'t help you at this moment", icon='question')

def exit_editor():
    if mb.askokcancel("Quit", "Do you really want to quit?"):
        gui.destroy()

# Disabled for testing
# gui.protocol('WM_DELETE_WINDOW', exit_editor) # override close button and redirect to exit_editor

menubar = Menu(gui)

# File menu,for open,save,save as and quit
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", accelerator='Alt+F4', command=exit_editor)
menubar.add_cascade(label="File", menu=filemenu)

# About menu - Aboutus, Help
aboutmenu = Menu(menubar, tearoff=0)
aboutmenu.add_command(label="About", command=about)
aboutmenu.add_cascade(label="Help", command=help_box)
menubar.add_cascade(label="About",  menu=aboutmenu)

# Returning defined setting for widget
gui.config(menu=menubar)

browseLabel = StringVar()
browseLabel.set("Selecteer een map: ")

def click():
    ext = ['.jpg', '.JPG', '.jpeg', '.JPEG']
    matches = []
    path = fd.askdirectory(initialdir='C:/Users/%s' % user)
    if path != "":
        browseLabel.set(path)

    for gui, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(tuple(ext)):
                matches.append(os.path.join(gui, file))
                print(file)

    # THE SAME CODE FAILES INSIDE FUNCTION

    img = "C:/Foto's\\P5270026.JPG"
    size = 100, 100
    pil_image = Image.open(img)
    pil_image.thumbnail(size, Image.ANTIALIAS)
    tk_image = ImageTk.PhotoImage(pil_image)
    # tk.Label(gui, image=tk_image).grid(row=1, column=0) # THIS LINE FAILED

    for img in matches:
        print("Match is %r" % img)


# THIS CODE WORKS OUTSIDE FUNCTION

# img = "C:/Foto's\\P5270026.JPG"
# size = 100, 100
# pil_image = Image.open(img)
# pil_image.thumbnail(size, Image.ANTIALIAS)
# tk_image = ImageTk.PhotoImage(pil_image)
# tk.Label(gui, image=tk_image, bg='brown').grid(row=1, column=0)

Label(gui, textvariable=browseLabel, bg="#4D4D4D", fg="#ffffff").grid(row=0, column=0, sticky='e')
Button(gui, text="Bladeren", command=click).grid(row=0, column=1, padx=2, pady=2, sticky='w', columnspan=9)

gui.mainloop()

1 个答案:

答案 0 :(得分:2)

您有一个名为gui的全局变量,它保存对根窗口的引用。在您的函数中,您将gui重用为包含字符串的局部变量。不要将相同的变量名称用于两个不同的目的。