我有我希望我的代码可以执行的所有操作,但是这个方块没有居中,这让我烦恼。我一直在网上搜索几个小时......请帮帮忙!我尝试过使用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()
答案 0 :(得分:1)
通过定义画布的高度和宽度并使用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()
您可以将矩形居中
答案 1 :(得分:0)
您的起始位置是通过调用draw方法设置的。您可以通过从画布对象计算它来自动检测正确的中心。
mkString
如果您愿意,也可以在draw方法中设置start_x和start_y。