Python图形化程序设计第6个练习,学习复选框(Checkbox)的使用:
程序代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import tkinter as tk #导入tkinter,并重新命名为tk,以后调用就可以少写代码 mywindow=tk.Tk() #新建窗口mywindow mywindow.title('A Window named by TAHO') #给窗口命名为 A Window named by TAHO mywindow.geometry('200x200') #窗口大小,300为宽,600为高,单位为像素px l=tk.Label(mywindow,text='empty', bg='yellow', width=20) #建立一个Label l.pack() #将Label显示到窗口中 def print_selection(): #定义函数 if(var1.get()==1)&(var2.get()==0): l.config(text='I only love Python.') elif(var1.get()==0)&(var2.get()==1): l.config(text='I only love C++.') elif(var1.get()==1)&(var2.get()==1): l.config(text='I love Python & C++.') else: l.config(text='I love neither') var1=tk.IntVar() var2=tk.IntVar() c1=tk.Checkbutton(mywindow,text='Python',variable=var1,onvalue=1,offvalue=0, command=print_selection) c1.pack() c2=tk.Checkbutton(mywindow,text='C++',variable=var2,onvalue=1,offvalue=0, command=print_selection) c2.pack() mywindow.mainloop() #循环刷新并显示窗口 |
运行结果:
Python图形化程序设计第7个练习,学习绘图(Canvas):
程序代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import tkinter as tk #导入tkinter,并重新命名为tk,以后调用就可以少写代码 mywindow=tk.Tk() #新建窗口mywindow mywindow.title('A Window named by TAHO') #给窗口命名为 A Window named by TAHO mywindow.geometry('300x350') #窗口大小,300为宽,350为高,单位为像素px canvas = tk.Canvas(mywindow, bg='lightblue', height=300, width=300) image_file = tk.PhotoImage(file='123.gif') image=canvas.create_image(10,10,anchor='nw',image=image_file) #nw=northwest x0,y0,x1,y1=200,200,250,250 line=canvas.create_line(x0,y0,x1,y1) #画线 oval=canvas.create_oval(x0,y0,x1,y1,fill='red') #圆形,带填充 arc=canvas.create_arc(x0+30,y0+30,x1+30,y1+30,start=0,extent=180) #扇形 rect=canvas.create_rectangle(250,20,250+30,20+30) #正方形 canvas.pack() def moveit(): #点击按钮移动的函数 canvas.move(rect,0,10) #将正方形向下移动10 b1 =tk.Button(mywindow, text='Move', command=moveit).pack() mywindow.mainloop() #循环刷新并显示窗口 |
运行效果。点击按钮方框会下移10个像素。