Polydynamical
Polydynamical

Reputation: 244

How store event.width in a variable in python?

I have a script that displays the dimensions of the tkinter window and I was wondering how I can set those values into a variable?

Here is the code:

import tkinter as tk
from tkinter import PhotoImage

root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack(fill="both", expand=True)

def canvas_changed(event):
    global WW
    WW = event.width
    global HH
    HH = event.height

img = PhotoImage(file="competeButton.png")
foo = canvas.create_image(image=img, width=WW, height=HH)
foo.pack(fill="both", expand=True)

root.mainloop()

Many thanks in advance for any help.

Upvotes: 0

Views: 163

Answers (2)

Polydynamical
Polydynamical

Reputation: 244

Create a class with all your image and the resizing of it. Then issue an if statement to call those values every time it changes. Here is an example of what you might do:

import tkinter as tk
from PIL import Image, ImageTk


class MainFrame(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.canvas = tk.Canvas(self)
        self.canvas.pack(fill=tk.BOTH, expand=1)
        self.canvas.bind("<Configure>", self.resize)
        self.img = ImageTk.PhotoImage(Image.open(r"competeButton.png"))
        self.canvas_img = self.canvas.create_image(0, 0, anchor="nw", image=self.img)

    def resize(self, event):
        img = Image.open(r"competeButton.png").resize((event.width, event.height), Image.ANTIALIAS)
        self.img = ImageTk.PhotoImage(img)
        self.canvas.itemconfig(self.canvas_img, image=self.img)


if __name__ == "__main__":
    main_frame = MainFrame()
    main_frame.mainloop()

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 386342

There's nothing special you have to do. Data is data, whether it comes from a widget or a database or anything else.

Here's an example that saves the value to a global variable:

def canvas_changed(event):
    global canvas_width
    canvas_width = event.width

Upvotes: 1

Related Questions