如何使 tkinter 矩形居中?

How can I center a tkinter rectangle?

我希望我的代码执行的所有操作都已准备就绪,但令我烦恼的是正方形未居中。我已经在互联网上搜索了几个小时...请帮忙!我试过使用 anchor = "center".place() 但我似乎无法正确使用它。

from tkinter import *
import random

class draw():
     def __init__(self, can, start_x, start_y, size):
     self.can = can
     self.id = self.can.create_rectangle((start_x, start_y,start_x+size, start_y+size), fill="red")
     self.can.tag_bind(self.id, "<ButtonPress-1>", self.set_color)
     self.color_change = True

def set_color(self,event = None):
    self.color_change = not self.color_change
    colors = ["red", "orange", "yellow", "green", "blue", "violet","pink","teal"]
    self.can.itemconfigure(self.id, fill = random.choice(colors))


root = Tk()
canvas = Canvas(root)
canvas.grid(column=1, row=1)
square = draw(canvas,1,1,90)


root.mainloop()

通过为 canvas 定义高度和宽度并使用 pack() 而不是 grid()(像这样)

from tkinter import *
import random

class draw():
     def __init__(self, can, start_x, start_y, size):
       self.can = can
       self.id = self.can.create_rectangle((start_x, start_y,start_x+size, start_y+size), fill="red")
       self.can.tag_bind(self.id, "<ButtonPress-1>", self.set_color)
       self.color_change = True

     def set_color(self,event = None):
        self.color_change = not self.color_change
        colors = ["red", "orange", "yellow", "green", "blue", "violet","pink","teal"]
        self.can.itemconfigure(self.id, fill = random.choice(colors))


WIDTH = 400 #change as needed
HEIGHT = 500 #change as needed
root = Tk()
canvas = Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
square = draw(canvas,WIDTH/2,HEIGHT/2,10)


root.mainloop()

您可以将矩形居中

您的起始位置是通过调用 draw 方法设置的。您可以通过从 canvas 对象计算它来自动检测正确的中心。

size = 90
center_height = canvas.winfo_reqheight() / 2 - size / 2
center_width = canvas.winfo_reqwidth() / 2 - size / 2
square = draw(canvas, center_width, center_height, size)

如果您愿意,也可以在绘图方法中设置 start_x 和 start_y。