Home > other >  Can you make two rectangles appear next to eachother using canvas?(Python)
Can you make two rectangles appear next to eachother using canvas?(Python)

Time:03-31

I am trying to showcase tables of monday and tuesday however the canvas rectangles seem to keep a very large gap between them.Is it possible to not have any gaps at all or have a very minimal gap?

class SmokingPlan:
def __init__(self, master):       
    self.master = master
    self.master.title('Kill Smoking')
    self.master.geometry("1200x1200")
    
    #Monday
    canvas_monday = Canvas(self.master)
    canvas_monday.grid(row = 0, column = 3)
    canvas_monday.create_rectangle(10,10, 150, 200)
    canvas_monday.create_text(60,25, text = "Monday")
    #Tuesday
    canvas_tuesday = Canvas(self.master)
    canvas_tuesday.grid(row=0, column = 5)
    canvas_tuesday.create_rectangle(10,10, 150, 200)
    canvas_tuesday.create_text(60,25, text = "Tuesday")

CodePudding user response:

It seems you are using tkinter. Using the .grid method will result in a gap. If you want more control over the position use .place instead.

CodePudding user response:

You are drawing two Canvas widgets. The Canvas widget has a default size. By changing the color of your canvas you will see why you have a gap in between.

import tkinter as tk

class SmokingPlan:
    def __init__(self, master):       
        self.master = master
        self.master.title('Kill Smoking')
        self.master.geometry("1200x1200")

        #Monday
        canvas_monday = tk.Canvas(self.master, bg="blue")
        canvas_monday.grid(row = 0, column = 0)
        canvas_monday.create_rectangle(10,10, 150, 200)
        canvas_monday.create_text(60,25, text = "Monday")
        #Tuesday
        canvas_tuesday = tk.Canvas(self.master, bg="yellow")
        canvas_tuesday.grid(row=0, column = 1)
        canvas_tuesday.create_rectangle(10,10, 150, 200)
        canvas_tuesday.create_text(60,25, text = "Tuesday")

if __name__ == '__main__':
    root = tk.Tk()
    app = SmokingPlan(root)
    root.mainloop()

enter image description here

Now you could set smaller canvas size or even better put both rectangles in the same canvas and change the coords.

Set Canvas size example:

canvas_monday = tk.Canvas(self.master, bg="blue", width=200)

will shrink your monday canvas as follow: enter image description here

  • Related