0

when add_button clicked choose_file function returns a path, how I can use this path if convert_button clicked?

def choose_file():
    filename = filedialog.askopenfilename(title="Open Images",
                                          filetypes=[('Image Files', '*.jpg'), ('Image Files', '*.png'),
                                                     ('Image Files', '*.jpeg'), ('Image Files', '*.gif'),
                                                     ('Image Files', '*.bmp')])
    if filename == "":
        messagebox.showwarning("Warning", "You didn`t specify any Images/s")
    print(filename)
    return filename
def convert(path, text):
    img = Image.open(path).convert("RGBA")
    txt = Image.new("RGBA", size=img.size, color=(255, 255, 255, 0))
    draw = ImageDraw.Draw(txt)

    # Creating text and font object
    text = text
    font = ImageFont.truetype(font="arial.ttf", size=70)

    # Positioning Text
    textwidth, textheight = draw.textsize(text, font)
    width, height = img.size
    x = width / 2 - textwidth / 2 + width / 15
    y = height - textheight - 10

    draw.text((x, y), text, fill=(255, 255, 255, 160), font=font)

    watermarked = Image.alpha_composite(img, txt)
    watermarked.save(r'watermarkedImage.png')
    
add_button = Button(window, text="Choose File", command=choose_file)
add_button.grid(row=2, column=1, sticky="w", ipady=8, ipadx=8)

convert_button = Button(text="Watermark", command=lambda: convert(path, text))
convert_button.grid(row=4, column=1, ipadx=8, ipady=8, sticky="w")

Basically, I try to watermark uploaded photos with python tkinter. There must be an easy solution, but I couldn't find yet. This is a tutorial level question.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Nuri
  • 1
  • 1

1 Answers1

0

save it to a variable inside choose_file, read from the variable inside convert. Return value of a command callback is ignored. The variable has to be available outside of the scope of choose_file function though, so you'd have to either encapsulate your GUI in a class (preferred way, imho) or define the variables as global.

matszwecja
  • 6,357
  • 2
  • 10
  • 17