tkinter模块高级操作(一)—— 透明按钮、透明文本框、自定义按钮及自定义文本框

【写在前面】

—— 众所周知,tkinter模块中自带的Button类是无法做到使其透明的(至少我无法做到)

【tip:透明是指让背景颜色或图片穿过按钮而显示出来】

—— 找遍了Button类的所有参数和操作,都无法解决这个问题!

—— 但!真的就没有办法做出一个透明的按钮吗?

—— 如果你认为只借助tkinter模块无法做到的话,请看下面的展示图!

震惊!这里面的按钮居然透明了!!!

这是我做的一个小游戏,完全用tkinter模块做成,没有用其他的模块!!!

链接放在这:Tkinter模块GUI图形化编程实战(八)——中国象棋(含超详解及完整源码、完整程序免费下载链接)_小康2022的博客-CSDN博客

—— 事实证明,用tkinter模块是可以做出透明的按钮的!

—— 还有透明的文本框!(原理是一样的)

快看呐!是透明的文本框诶!!!

这个是我做的另外一个未完成的作品,暂无链接哈

—— 不知大家是否已经想到博主是用什么方法做到的呢?

【tip:看文章标题其实你就知道方法了】


【正片开始】

【原理解说】

在tkinter模块里面只用内置的Button类确实改变不了它不透明这个事实,而且它是已经封装好了的类,就算你去继承它,重新创建一个属于自己的类,也不容易改变这个事实(因为原理不同),对于按钮(Button类)而言,它的外框和里面的部分是一个整体,无法分割,更不用说要让它里面的部分与外界的图片产生什么联系了。除非……

—— 有的人认为,不就是做个透明的按钮吗?这谁不会,我在背景上放一张图片,然后再裁剪该图片使其到正确的位置,最后在Button类上插入该裁剪了的图片不就是“透明”的啦?

—— 博主:不会吧不会吧,不会真的有人这样做吧?(震惊中……)

—— 博主:那我现在要一亿个这样的按钮嘞?你是不是要裁剪一亿次嘞???

实际上,上述也算是让按钮透明的一种方法,只不过这种透明是“假透明”,并不是真正的透明。

—— 又有人认为,我管它是不是真透明!能用不就好了?

—— 博主:先不说你这是否浪费内存,下面的操作“假透明”能实现吗?

真 · 透明按钮

看到这里,了解过tkinter模块的应该已经知道了原理。

这个透明是真的,但按钮是假的!

按钮是我们自己在Canvas控件上“画”出来的,再利用bind函数来对其关联一些事件,于是就得到了一个类似于按钮的“虚假按钮”。

它相对于“假透明”的按钮而言,优点在于按钮的样式我们可以自己设计,而“假透明”的按钮无法做到,因为它实际上是继承于Button类的,无法再对其重新修改,缺点呢,后面也会非常明显的看到,就是这个按钮样式的设置非常地让人烦恼,因为坐标位置的处理很麻烦(T_T)

不多说了,下面就上代码吧!

【代码演示】

【目标要求】做出一个矩形的“真透明”按钮,适当加一点样式

【功能实现】点击可以print出“Hello Python!”

这里我先把背景图给出来(如下)

背景图片(来源于互联网)

 来!上代码!!!

from tkinter import *# 引入模块

root = Tk()# 创建Tk控件
root.geometry('960x480+200+100')# 设置窗口大小及位置
root.title('透明按钮')# 设置窗口标题

canvas = Canvas(root,highlightthickness=0)# 创建Canvas控件,并设置边框厚度为0
canvas.place(width=960,height=480)# 设置Canvas控件大小及位置
bg = PhotoImage(file='background.png')# 【这里记得要改成对应的路径】

canvas.create_image(480,240,image=bg)# 添加背景图片
r1 = canvas.create_rectangle(380,350,580,400,width=2,outline='black')# 按钮外框
r2 = canvas.create_rectangle(380+3,350+3,580-3,400-3,width=2,outline='black')# 按钮内框
t = canvas.create_text(480,375,text='点 我',font=('楷体',20,'bold'),fill='black')# 按钮显示文本

canvas.bind('<Button-1>',lambda event:bind_1(event))# 关联鼠标点击事件
canvas.bind('<Motion>',lambda event:bind_2(event))# 关联鼠标经过事件

def bind_1(event):# 点击响应函数
    if 380<=event.x<=580 and 350<=event.y<=400:# 响应的位置
        print('Hello Python!')# 打印

def bind_2(event):# 鼠标经过响应函数
    if 380<=event.x<=580 and 350<=event.y<=400:# 响应的位置
        canvas.itemconfigure(r1,outline='white')# 重设外框颜色
        canvas.itemconfigure(r2,outline='white')# 重设内框颜色
        canvas.itemconfigure(t,fill='white')# 重设显示文本颜色
    else:
        canvas.itemconfigure(r1,outline='black')# 恢复外框默认颜色
        canvas.itemconfigure(r2,outline='black')# 恢复内框默认颜色
        canvas.itemconfigure(t,fill='black')# 恢复显示文本默认颜色

root.mainloop()# 窗口进入消息事件循环

效果如下

透明按钮效果展示

还有更多的样式可由我们自行开发哦!(完美诠释什么叫自定义!)

比如下面这样的样式(虽然不是透明,但它的形状用Button类绝对做不到!)

【tip:鼠标的样式在经过按钮时改变了哦!】

自定义按钮效果展示

代码呢,如下(其实相较于上面的代码,只改了一点点) 

from tkinter import *# 引入模块

root = Tk()# 创建Tk控件
root.geometry('960x480+200+100')# 设置窗口大小及位置
root.title('自定义按钮')# 设置窗口标题

canvas = Canvas(root,highlightthickness=0)# 创建Canvas控件,并设置边框厚度为0
canvas.place(width=960,height=480)# 设置Canvas控件大小及位置
bg = PhotoImage(file='background.png')# 【这里记得要改成对应的路径】

canvas.create_image(480,240,image=bg)# 添加背景图片
r = canvas.create_rectangle(380,350-1,580,400+1,width=0,fill='yellow')# 按钮外框
c1 = canvas.create_oval(355,350,405,400,width=0,fill='yellow')# 按钮左圆
c2 = canvas.create_oval(555,350,605,400,width=0,fill='yellow')# 按钮右圆
t = canvas.create_text(480,375,text='点 我',font=('楷体',20,'bold'),fill='black')# 按钮显示文本

canvas.bind('<Button-1>',lambda event:bind_1(event))# 关联鼠标点击事件
canvas.bind('<Motion>',lambda event:bind_2(event))# 关联鼠标经过事件

def bind_1(event):# 点击响应函数
    if 380<=event.x<=580 and 350<=event.y<=400:# 响应的位置
        print('Hello Python!')# 打印

def bind_2(event):# 鼠标经过响应函数
    if 380<=event.x<=580 and 350<=event.y<=400:# 响应的位置
        canvas.itemconfigure(r,fill='orange')# 重设外框颜色
        canvas.itemconfigure(c1,fill='orange')# 重设左圆颜色
        canvas.itemconfigure(c2,fill='orange')# 重设右圆颜色
        canvas.itemconfigure(t,fill='white')# 重设显示文本颜色
        canvas.configure(cursor='hand2')# 重设鼠标样式
    else:
        canvas.itemconfigure(r,fill='yellow')# 恢复外框默认颜色
        canvas.itemconfigure(c1,fill='yellow')# 恢复左圆默认颜色
        canvas.itemconfigure(c2,fill='yellow')# 恢复右圆默认颜色
        canvas.itemconfigure(t,fill='black')# 恢复显示文本默认颜色
        canvas.configure(cursor='arrow')# 恢复鼠标样式

root.mainloop()# 窗口进入消息事件循环

那么,看到了这里,想必大家也应该知道了透明的文本框是怎么做出来的吧?简单说,“画”出来的!

自定义透明文本框效果展示

温馨提示哈,下面代码里的 Entry_Canvas 类在下面的【大礼包】中有哦!

from tkinter import *

class Entry_Canvas:
    ## ------- 画布文本框类 ------- ##
    def __init__(self,canvas:Canvas,x:int,y:int,r_width:int,r_height:int,text1:str,text2:str,pw_mode:bool=False,d_outline:str='gray',d_fill:str='gray',fontsize:int=15):
        self.canvas = canvas#父控件
        self.focus = False#是否获取到当前焦点
        self.mode = pw_mode#密码模式
 
        self.value = ''#真实值
        self.info = ''#表面值
 
        self.x1 = x-r_width#左上角x坐标
        self.y1 = y-r_height#左上角y坐标
        self.x2 = x+r_width#右下角x坐标
        self.y2 = y+r_height#右下角y坐标
        self.info1 = text1#未获取焦点时文本显示
        self.info2 = text2#半获取焦点时文本显示
        self.d_outline = d_outline#默认外框颜色
        self.d_fill = d_fill#默认文字颜色
 
        self.rec = self.canvas.create_rectangle(x-r_width,y-r_height,x+r_width,y+r_height,width=2,outline=d_outline)
        self.tex = self.canvas.create_text(x,y,text=self.info1,font=('楷体',fontsize),fill=d_fill)
 
    def focus_on(self,color:str):
        ## ------ 焦点已获取状态 ------ ##
        self.focus = True
        self.canvas.itemconfig(self.rec,outline=color)
        self.canvas.itemconfig(self.tex,text=self.info+'|')
 
    def focus_off(self):
        ## ------ 焦点未获取状态 ------ ##
        self.focus = False
        self.canvas.itemconfig(self.rec,outline=self.d_outline)
 
        if self.info == '':
            self.canvas.itemconfig(self.tex,text=self.info1)
        else:
            self.canvas.itemconfig(self.tex,text=self.info)
    
    def Focus(self,event:Event,color:str='white'):
        ## ------- 焦点获取状态检测 ------- ##
        if self.x1<=event.x<=self.x2 and self.y1<=event.y<=self.y2:
            self.focus_on(color)
        else:
            self.focus_off()
 
    def move_on(self,color:str):
        ## ------ 焦点半获取状态 ------ ##
        if self.focus == False:
            self.canvas.itemconfig(self.rec,outline=color)
            if self.canvas.itemcget(self.tex,'text') == self.info1:
                self.canvas.itemconfig(self.tex,text=self.info2)
    
    def move_off(self):
        ## ------ 焦点非半获取状态 ------ ##
        if self.focus == False:
            self.canvas.itemconfig(self.rec,outline=self.d_fill)
            if self.canvas.itemcget(self.tex,'text') == self.info2:
                self.canvas.itemconfig(self.tex,text=self.info1)
 
    def Move(self,event:Event,color:str='white'):
        ## ------- 焦点半获取状态检测 ------- ##
        if self.x1<=event.x<=self.x2 and self.y1<=event.y<=self.y2:
            self.move_on(color)
        else:
            self.move_off()
 
    def input(self,char:str,length:int=10):
        ## ------ 文本输入 ------ ##
        if self.focus == True:
            
            value = ord(char)
            if value == 8:
                self.value = self.value[:-1]
            elif value<=47 or 58<=value<=64 or 91<=value<=96 or 123<=value<=256:
                pass
            else:
                if len(self.value) < length and not char.isspace():
                    self.value += char
 
            if self.mode == True:
                self.info = '•'*len(self.value)
            else:
                self.info = self.value
 
            self.canvas.itemconfig(self.tex,text=self.info+'|')

## 窗口初始化部分
root = Tk()
root.title('透明文本框')
root.geometry('960x480+150+100')
root.resizable(0,0)
canvas = Canvas(root,highlightthickness=0)
background = PhotoImage(file='background.png')#【记得改路径哦】
canvas.create_image(480,240,image=background)
canvas.place(width=960,height=480)

## 自定义透明输入框对象实例化
My_Entry = Entry_Canvas(canvas,480,400,100,15,'密码','点击输入密码',True)
#参数解释(按顺序):父画布控件,文本框中心的横坐标,中心的纵坐标,半长(类似于半径),半宽,显示文本,鼠标移动上去时显示的文本,是否密码模式(True或者False)【还有一些参数,自己看看,选择性取用】
root.bind('<Button-1>',lambda event:My_Entry.Focus(event))#关联点击
root.bind('<Motion>',lambda event:My_Entry.Move(event))#关联鼠标移动
root.bind('<Any-Key>',lambda event:My_Entry.input(event.char))#关联键盘输入

## 窗口进入消息事件循环
root.mainloop()

当然,要解决大量透明按钮和透明文本框的需求,我们肯定不能这样子,每个按钮或文本框都去设置它的位置啊,样式啊什么的(重复工作太多了),所以,我们可以用类实现!类就不用大家写了,我这里特意为大家准备了一份大礼包!(如下)不过大家也可以修改下面的类,使其符合自己的设计要求!

上代码!

【大礼包】

【画布按钮类】

class Button_Canvas:
    ## ------- 画布按钮类 ------- ##
    def __init__(self,canvas:Canvas,x1:int,y1:int,x2:int,y2:int,text:str,fontsize:int=15,d_outline:str='gray',d_fill:str='gray',image:PhotoImage=None):
        self.canvas = canvas#父控件
        self.value = text
        self.tag = text

        self.x1 = x1#左上角x坐标
        self.y1 = y1#左上角y坐标
        self.x2 = x2#右下角x坐标
        self.y2 = y2#右下角y坐标
        self.d_outline = d_outline#默认外框颜色
        self.d_fill = d_fill#默认文字颜色

        self.rec = self.canvas.create_rectangle(x1,y1,x2,y2,width=2,outline=self.d_outline,tag=self.tag)
        self.tex = self.canvas.create_text((x1+x2)//2,(y1+y2)//2,text=self.value,font=('楷体',fontsize),justify='center',fill=self.d_fill,tag=self.tag)

        if image != None:
            self.canvas.create_image((x1+x2)//2,(y1+y2)//2,image=image)

    def focus_on(self,color:str):
        ## ------ 焦点已获取状态 ------ ##
        self.canvas.itemconfig(self.rec,fill=color)

    def focus_off(self):
        ## ------ 焦点未获取状态 ------ ##
        self.canvas.itemconfig(self.rec,fill='')

    def Focus(self,event:Event,color:str):
        ## ------ 焦点获取状态检测 ------ ##
        if self.x1<=event.x<=self.x2 and self.y1<=event.y<=self.y2:
            self.focus_on(color)
        else:
            self.focus_off()

    def move_on(self,color:str):
        ## ------ 焦点半获取状态 ------ ##
        self.canvas.itemconfig(self.rec,outline=color)
        self.canvas.itemconfig(self.tex,fill=color)
    
    def move_off(self):
        ## ------ 焦点非半获取状态 ------ ##
        self.canvas.itemconfig(self.rec,outline=self.d_outline)
        self.canvas.itemconfig(self.tex,fill=self.d_fill)
    
    def Move(self,event:Event,color:str):
        ## ------ 焦点半获取状态检测 ------ ##
        if self.x1<=event.x<=self.x2 and self.y1<=event.y<=self.y2:
            self.move_on(color)
        else:
            self.move_off()

    def execute(self,event:Event,function=None):
        ## ------- 执行关联函数 ------- ##
        if self.x1<=event.x<=self.x2 and self.y1<=event.y<=self.y2:
            self.focus_off()
            self.move_off()
            
            if function != None:
                return function()

    def value_change(self,value:str):
        ## ------ 显示值改变 ------ ##
        self.value = value
        self.canvas.itemconfig(self.tex,text=self.value)

    def destroy(self):
        ## ------ 按钮删除 ------ ##
        self.canvas.delete(self.tag)

【画布文本框类】

class Entry_Canvas:
    ## ------- 画布文本框类 ------- ##
    def __init__(self,canvas:Canvas,x:int,y:int,r_width:int,r_height:int,text1:str,text2:str,pw_mode:bool=False,d_outline:str='gray',d_fill:str='gray',fontsize:int=15):
        self.canvas = canvas#父控件
        self.focus = False#是否获取到当前焦点
        self.mode = pw_mode#密码模式

        self.value = ''#真实值
        self.info = ''#表面值

        self.x1 = x-r_width#左上角x坐标
        self.y1 = y-r_height#左上角y坐标
        self.x2 = x+r_width#右下角x坐标
        self.y2 = y+r_height#右下角y坐标
        self.info1 = text1#未获取焦点时文本显示
        self.info2 = text2#半获取焦点时文本显示
        self.d_outline = d_outline#默认外框颜色
        self.d_fill = d_fill#默认文字颜色

        self.rec = self.canvas.create_rectangle(x-r_width,y-r_height,x+r_width,y+r_height,width=2,outline=d_outline)
        self.tex = self.canvas.create_text(x,y,text=self.info1,font=('楷体',fontsize),fill=d_fill)

    def focus_on(self,color:str):
        ## ------ 焦点已获取状态 ------ ##
        self.focus = True
        self.canvas.itemconfig(self.rec,outline=color)
        self.canvas.itemconfig(self.tex,text=self.info+'|')

    def focus_off(self):
        ## ------ 焦点未获取状态 ------ ##
        self.focus = False
        self.canvas.itemconfig(self.rec,outline=self.d_outline)

        if self.info == '':
            self.canvas.itemconfig(self.tex,text=self.info1)
        else:
            self.canvas.itemconfig(self.tex,text=self.info)
    
    def Focus(self,event:Event,color:str='white'):
        ## ------- 焦点获取状态检测 ------- ##
        if self.x1<=event.x<=self.x2 and self.y1<=event.y<=self.y2:
            self.focus_on(color)
        else:
            self.focus_off()

    def move_on(self,color:str):
        ## ------ 焦点半获取状态 ------ ##
        if self.focus == False:
            self.canvas.itemconfig(self.rec,outline=color)
            if self.canvas.itemcget(self.tex,'text') == self.info1:
                self.canvas.itemconfig(self.tex,text=self.info2)
    
    def move_off(self):
        ## ------ 焦点非半获取状态 ------ ##
        if self.focus == False:
            self.canvas.itemconfig(self.rec,outline=self.d_fill)
            if self.canvas.itemcget(self.tex,'text') == self.info2:
                self.canvas.itemconfig(self.tex,text=self.info1)

    def Move(self,event:Event,color:str='white'):
        ## ------- 焦点半获取状态检测 ------- ##
        if self.x1<=event.x<=self.x2 and self.y1<=event.y<=self.y2:
            self.move_on(color)
        else:
            self.move_off()

    def input(self,char:str,length:int=10):
        ## ------ 文本输入 ------ ##
        if self.focus == True:
            
            value = ord(char)
            if value == 8:
                self.value = self.value[:-1]
            elif value<=47 or 58<=value<=64 or 91<=value<=96 or 123<=value<=256:
                pass
            else:
                if len(self.value) < length and not char.isspace():
                    self.value += char

            if self.mode == True:
                self.info = '•'*len(self.value)
            else:
                self.info = self.value

            self.canvas.itemconfig(self.tex,text=self.info+'|')

【拿去用吧!不用谢了!给个赞和收藏我就满意啦!】

物联沃分享整理
物联沃-IOTWORD物联网 » tkinter模块高级操作(一)—— 透明按钮、透明文本框、自定义按钮及自定义文本框

发表评论