Ad

How Can I Set The Width Of A Canvas To The Width Of The Screen In Python Tkinter?

- 1 answer

I have a canvas in tkinter that needs to span the whole width of the screen, but cannot get it to work.

I tried to make the screen width a variable and pass it along as a parameter in the class but throws a error at me, I tried to set the root.winfo_screenwidth to self.winfo_screenwidth but it just throws a error at me, I looked on the www for answers but the closest thing I saw was how to set the root to the screen size.

Here is my code:

import tkinter as tk


class Window(tk.Frame):
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)

        canvas = tk.Canvas(self, width="", height=100) #How to set the width to the screen width?
        canvas.config(bg="#505050")
        canvas.pack()


def mainloop_scw():
    root = tk.Tk()
    root.title("Editor - Adventure")
    screenwidth = root.winfo_screenwidth()
    screenheight = root.winfo_screenheight()
    root.geometry("%sx%s" %(screenwidth, screenheight))
    root.config(bg="#303030")
    app = Window(root)
    app.config(bg="#303030")
    app.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
    root.mainloop()


if __name__ == "__main__":
    mainloop_scw()

Does anyone know how I can set the canvas width to screenwidth?

Ad

Answer

You don't need to explicitly set the width of the canvas. pack has options that you can use to force the canvas to occupy the full width of the screen.

canvas.pack(fill="x")
Ad
source: stackoverflow.com
Ad