我正在尝试制作一个绘画类型程序,在其中可以绘制多种不同的形状,并且试图使用颜色选择器更改要绘制的形状的颜色。我不知道该怎么做。
我一周前才开始编码,不知道如何解决问题,但是我尝试添加不同的变量集作为所选颜色。
def getColor():
color = askcolor()
def line():
a = (asl.get())
b = (bsl.get())
c = (csl.get())
d = (dsl.get())
fill = color
cnv.create_line(a, b, c, d)
def rect():
a = (asl.get())
b = (bsl.get())
c = (csl.get())
d = (dsl.get())
fill = color
cnv.create_rectangle(a, b, c, d)
def circ():#center coordinates, radius
a = (asl.get())
b = (bsl.get())
c = (csl.get())
d = (dsl.get())
fill = color
cnv.create_oval(a, b, c, d)
from tkinter import *
from tkinter.colorchooser import *
cp=Tk()
cnv=Canvas(cp, width = 600, height = 600, bg = 'white')
cnv.grid(row = 2, column = 5, padx = 3, pady = 3)
#this is the control panel for the shape maker
exitbtn=Button(cp, text = 'Exit', command = exit)
exitbtn.grid(row = 0, column = 1, padx = 3, pady = 3)
linebtn=Button(cp, text = 'line', command = line)
linebtn.grid(row = 0, column = 2, padx = 3, pady = 3)
rectbtn=Button(cp, text = 'Rectangle', command = rect)
rectbtn.grid(row = 0, column = 3, padx = 3, pady = 3)
circbtn=Button(cp, text = 'Circle', command = circ)
circbtn.grid(row = 0, column = 4, padx = 3, pady = 3)
colrbtn=Button(cp, text = 'Color', command = getColor)
colrbtn.grid(row = 0, column = 5, padx = 3, pady = 3)
#changes the x amd y values for the corners of the shape
asl = Scale(cp, from_=0, to=600, length = 200, tickinterval=50)
asl.set(0)
asl.grid(row=6, column=1, padx=3,pady=3)
bsl = Scale(cp, from_=0, to=600, length = 200)
bsl.set(0)
bsl.grid(row=6, column=2, padx=3,pady=3)
csl = Scale(cp, from_=0, to=600, length = 200)
csl.set(0)
csl.grid(row=6, column=3, padx=3,pady=3)
dsl = Scale(cp, from_=0, to=600, length = 200)
dsl.set(0)
dsl.grid(row=6, column=4, padx=3,pady=3)
#labels that tell what the sliders do
x1 = Label(cp, text="x1")
x1.grid(row=5, column=1, padx=3,pady=3)
y1 = Label(cp, text="y1")
y1.grid(row=5, column=2, padx=3,pady=3)
x2 = Label(cp, text="x2")
x2.grid(row=5, column=3, padx=3,pady=3)
y2 = Label(cp, text="y2")
y2.grid(row=5, column=4, padx=3,pady=3)
mainloop()
我希望它使用十六进制值作为变量,并用我选择的颜色填充形状。
答案 0 :(得分:0)
您需要在设置color
的任何函数中将其定义为全局变量。 global
表示该变量在文件中的任何位置都可用。
第一步是将getColor
修改为包含global
语句。同样,重要的是要知道askcolor
返回一个元组,第二个值是在创建画布项目时可以使用的颜色规范。那就是应该保存的值
def getColor():
global color
color = askcolor()[1]
下一步是修改您的函数以在创建对象时使用它。例如,您的rect
函数可能看起来像这样:
def rect():
a = (asl.get())
b = (bsl.get())
c = (csl.get())
d = (dsl.get())
cnv.create_rectangle(a, b, c, d, fill=color)