python - 如何将 tkinter 矩形居中?

标签 python python-3.x tkinter centering drawrectangle

我已经拥有了我希望代码执行的所有功能,但令我烦恼的是正方形不居中。我已经在互联网上搜索了几个小时......请帮忙!我尝试过使用 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()

您可以将矩形居中

关于python - 如何将 tkinter 矩形居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49396415/

相关文章:

python - Tkinter:抓取 ScrolledText 文本板的内容

python - 如何获取Python数据框中的最后n个索引?

Python xlsxwriter : How do I write a formula that references a different sheet

Python 网格列跨度

python - Pyinstaller 3.3.1 & 3.4.0-dev 使用 apscheduler 构建

python - plotly 尖峰未出现在次要 plotly 上

Python如何使用.pack作为其他显示器分辨率?

python - 如何修复 "update-alternatives: warning: forcing reinstallation of alternative/usr/bin/python3.8 because link group python3 is broken"?

python - 逻辑回归中的混淆矩阵

python - 当重复的 ID 有付款日期时创建新列( Pandas 数据框)