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