image = ImageTk.PhotoImage с переменными - PullRequest
0 голосов
/ 30 января 2019

Итак, я хочу открыть изображение с помощью image = ImageTk.PhotoImage(), и оно прекрасно работает с

image = ImageTk.PhotoImage(file="C:/Users/timol/PycharmProjects/Test1/haha.jpg")

Ранее в коде я сохранил путь к переменной, равной

def click():
    file = askopenfilename(initialdir='C:/Users/%s')
    directory = os.path.split(file)[0]
    print(directory)

Теперь я хочу использовать путь, сохраненный в «директории», для ввода image = ImageTk.PhotoImage(file= "directory") Но это просто дает мне много ошибок.

Если вам нужно знать, я хочу это сделать,потому что я хочу, чтобы пользователь позже мог загружать изображение и отображать / использовать в программе.

вот весь код:

`from tkinter import *
from PIL import ImageTk, Image, ImageDraw
import PIL
import os
from tkinter import filedialog

root = Tk()
root.title("Zahlenerfassung")
root.geometry("500x400")
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
def create(): command=os.system("start "+"pepsi.txt")
#def click():
    # Get the file
   # file = askopenfilename(initialdir='C:/Users/%s')
    # Split the filepath to get the directory
#  directory = os.path.split(file)[0]
#   print(directory)

def click():
     image_file_location = filedialog.askopenfilename(initialdir="C:/Users/%s")
     image = ImageTk.PhotoImage(file=image_file_location)
     canvas.create_image(50, 50, image=image, anchor=NW)

button1 = Button(topFrame, text="Bild auswerten", fg="red")
button2 = Button(bottomFrame, text="Erstelle ein Bild", fg="blue", command=lambda: create())
button3 = Button(bottomFrame, text="Lade dein Bild hoch", fg="blue", command=lambda: click())

canvas = Canvas(width=200, height=200)
canvas.pack(expand=NO, fill=NONE)

button1.pack(side=LEFT)
button2.pack(side=LEFT)
button3.pack(side=LEFT)

one = Label(root, text="", fg="white")
one.pack(fill=BOTH, expand=TRUE)
root.mainloop()

Ответы [ 2 ]

0 голосов
/ 30 января 2019

Я использовал askopenfile() & его атрибут name, чтобы получить имя файла.PhotoImage принимает файл изображения типа Image.open().Я проверил этот код, и изображение появляется внутри окна холста.

from tkinter import filedialog, Tk, Canvas, NW, NO, NONE, mainloop
import os
from PIL import ImageTk, Image


canvas = Canvas(width=200, height=200)
canvas.pack(expand=NO, fill=NONE)
image_file_loc = filedialog.askopenfile(initialdir=r'C:\Users')
file_path = image_file_loc.name
image = Image.open(file_path)
tk_image = ImageTk.PhotoImage(image)
canvas.create_image(50, 50, image=tk_image, anchor=NW)
mainloop()
0 голосов
/ 30 января 2019

Вы можете попробовать это:

from tkinter import *
from PIL import ImageTk, Image
import os
from tkinter import filedialog

root = Tk()
root.title("Zahlenerfassung")
root.geometry("500x400")
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
def create():
    command=os.system("start "+"pepsi.txt")

def click():
     image_file_location = filedialog.askopenfilename(initialdir="C:/Users/%s")
     img = Image.open(image_file_location)
     canvas.image = ImageTk.PhotoImage(img.resize((200, 200), Image.ANTIALIAS))     #  this line is for resizing the image to fit canvas size
     # canvas.image = ImageTk.PhotoImage(img)   #  you have to use this line instead of the upper line if you don't want resizing
     canvas.create_image(0, 0, image=canvas.image, anchor='nw')

button1 = Button(topFrame, text="Bild auswerten", fg="red")
button2 = Button(bottomFrame, text="Erstelle ein Bild", fg="blue", command=lambda: create())
button3 = Button(bottomFrame, text="Lade dein Bild hoch", fg="blue", command=lambda: click())

canvas = Canvas(width=200, height=200)
canvas.pack(expand=NO, fill=NONE)

button1.pack(side=LEFT)
button2.pack(side=LEFT)
button3.pack(side=LEFT)

one = Label(root, text="", fg="white")
one.pack(fill=BOTH, expand=TRUE)
root.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...