案例:通过控制RGB三个滑动条,使得区域内颜色实时变化。
import Tkinter as tk
window=tk.Tk()
#定义了一个滑动条
#slider=tk.Scale(window,from_=0,to=100)
#定义滚动滑动条的时候需要更新
def sliderUpdate(source):
red=redSlider.get()
green=greenSlider.get()
blue=blueSlider.get()
colour = "#%02x%02x%02x" % (red,green , blue)
# print colour
canvas.config(bg=colour)
redSlider=tk.Scale(window,from_=0,to=255,command=sliderUpdate)
greenSlider=tk.Scale(window,from_=0,to=255,command=sliderUpdate)
blueSlider=tk.Scale(window,from_=0,to=255,command=sliderUpdate)
canvas=tk.Canvas(window,width=200,height=200)
redSlider.grid(row=1,column=1)
greenSlider.grid(row=1,column=2)
blueSlider.grid(row=1,column=3)
canvas.grid(row=2,column=1,columnspan=3)
tk.mainloop()
加上一个文本框用来显示此时颜色的值
import Tkinter as tk
window=tk.Tk()
#定义了一个滑动条
#slider=tk.Scale(window,from_=0,to=100)
#定义滚动滑动条的时候需要更新
def sliderUpdate(source):
red=redSlider.get()
green=greenSlider.get()
blue=blueSlider.get()
colour = "#%02x%02x%02x" % (red,green , blue)
# print colour
canvas.config(bg=colour)
#下面的文本框用来显示此时区域内颜色数值
hexText.delete(0,tk.END)
hexText.insert(0,colour)
redSlider=tk.Scale(window,from_=0,to=255,command=sliderUpdate)
greenSlider=tk.Scale(window,from_=0,to=255,command=sliderUpdate)
blueSlider=tk.Scale(window,from_=0,to=255,command=sliderUpdate)
canvas=tk.Canvas(window,width=200,height=200)
#定义一个文本框,然后将十六进制的数值显示到里面
hexText=tk.Entry(window)
redSlider.grid(row=1,column=1)
greenSlider.grid(row=1,column=2)
blueSlider.grid(row=1,column=3)
canvas.grid(row=2,column=1,columnspan=3)
#显示颜色数值文本框的位置
hexText.grid(row=3,column=1,columnspan=3)
tk.mainloop()
案例:点击一定的按钮次数,显示时间
import Tkinter as tk
import time
window=tk.Tk()
clicks=0
start=0
goal=10
#定义一个点击按钮的函数
def buttonclick():
global clicks
global start
if clicks==0:
start=time.time()
clicks=clicks+1
elif clicks+1>=goal:
score=time.time()-start
label.config(text="time"+str(score))
clicks=0
else:
clicks=clicks+1
slider.set(clicks)
button = tk.Button(window,text='click me',command=buttonclick)
slide=tk.Scale(window,from_=0,to=goal)
label=tk.Label(window)
button.pack()
slide.pack()
label.pack()
window.mainloop()
注意此行代码:
colour="#%02x%02x%02x"%(red,green,blue) #作用是将三基色赋值给colour