-1
3天前我開始學習Python,所以我是一個新手。 我想要的是選擇一個目錄並顯示其中的圖像。 當tk.Label是功能外「點擊」它工作正常,但內部功能「點擊」它拋出: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()
@Turmin加上:不要使用全局變量。 – BlackJack
@Bryan謝謝你。我改變了這個,錯誤被解決了,但是我得到了一個白色的正方形而不是圖像。 我試過pil_image = Image.open(open(img,'rb')),而不是pil_image = Image.open(img),但這並不重要。 – Michael
有些奇怪的是;如果我之後發生錯誤,比圖像顯示。我不明白。我怎樣才能向你展示代碼?我必須改變我的第一篇文章嗎? – Michael