canvas中的控件
canvas中所有控件定义生成好后,后加pack/grid/place,加以显示。
用tkinter.pack设计复杂界面布局
生成canvas
def showCanvas(self): #显示画布
self.canvas_1 = tkinter.Canvas(width=500,height=50,bg="red")
self.canvas_1.pack(side='top',expand='no',fill='x')
self.canvas_2 = tkinter.Canvas(width=100,height=100,bg='yellow')
self.canvas_2.pack(side='left',anchor='nw',fill='y')
self.canvas_3 = tkinter.Canvas(bg='white')
self.canvas_3.pack(side='left',expand='yes',fill='both',padx=5,pady=5)
button
生成对象 = tkinter.Button(画布,长,宽,command,image)
command和bind用来绑定控件的功能函数
#####文件的路径#########
C_PATH = "F:\\py_pro\\electricBox\\venv\\log\\CC.png"
R_PATH = "F:\\py_pro\\electricBox\\venv\\log\\RR.png"
L_PATH = "F:\\py_pro\\electricBox\\venv\\log\\LL.png"
def addButton(self):
photo_C = tkinter.PhotoImage(file=C_PATH)
self.button_show_R = tkinter.Button(self.canvas,width=100,height=50,image=photo_C).pack(side='top')
photo_R = tkinter.PhotoImage(file=R_PATH)
self.button_show_R = tkinter.Button(self.canvas,width=100,height=50,image=photo_R).pack(side='top')
photo_L = tkinter.PhotoImage(file=L_PATH)
self.button_show_R = tkinter.Button(self.canvas,width=100,height=50,image=photo_L).pack(side='top')
控件Button和其他控件都可以插入图片
Label
def addLabel(self):
self.Label1 = tkinter.Label(self.canvas_1,width=50,foreground='blue',text='Input information:')
self.Label1.pack(side='left')
Entry
简单的文本框输入,以“回车”触发
def getEntry(self):
self.input_var = tkinter.StringVar()
self.inputEntry = tkinter.Entry(self.canvas,textvariable=self.input_var)
self.inputEntry.bind('<Return>',self.Analysis_Creat)
self.inputEntry.pack(side='left')
combox
下拉框默认可以在框里输入信息,将state设为“readonly”,即没有输入信息的功能
def combox(self):
self.comboxText = tkinter.StringVar()
self.combox = tkinter.ttk.Combobox(self.canvas,width=10,textvariable=self.comboxText,state='readonly')
self.combox['value'] = ('电阻','电容','电感','短路','断路')
self.combox.pack(side= 'left')
画布中画直线
在画布中,用鼠标画直线,
################## Start canvas中画线 ############################
def paintLine(self):
self.canvas.bind('<Button-1>',self.getStartPosition)
self.canvas.bind('<ButtonRelease-1>', self.getEndPosition)
def getStartPosition(self,event):
self.x_Start_position = event.x
self.y_Start_position = event.y
print(self.x_Start_position,self.y_Start_position)
def getEndPosition(self,event):
self.x_End_position = event.x
self.y_End_position = event.y
print(self.x_End_position, self.y_End_position)
if abs(self.x_End_position - self.x_Start_position) > abs(self.y_End_position - self.y_Start_position):
self.line1 = self.canvas.create_line(self.x_Start_position,self.y_Start_position,
self.x_End_position,self.y_Start_position)
else:
self.line1 = self.canvas.create_line(self.x_Start_position,self.y_Start_position,
self.x_Start_position,self.y_End_position)