• [bug]tkinter事件触发


    在python的tkinter中,写代码出了bug,找了好半天,记一下。

    import tkinter as tk
    from tkinter import Frame
    from  tkinter import messagebox
    from  tkinter import font
    window = tk.Tk()#界面
    the_width,the_height = window.maxsize()#全屏的长、宽
    button_list = list()#按钮列表
    each_width_height = 83//9#每个按钮的边长
    now_x = 0#当前位置的横坐标(0~8,左侧为x轴,上方为y轴)
    now_y = 0
    
    #设置屏幕标题
    window.title("阿尔法猪数独")
    #设置屏幕大小
    window.geometry("{}x{}".format(the_width, the_height))
    
    
    
    #字体
    f1 = font=('Arial', 12,'bold')
    shuzi = "娃哈哈"
    #设置标签文字
    text = tk.Label(window, text='数独游戏', bg='green',font=('Arial', 12), width=30, height=2,)
    #放置标签
    text.place(x = 90*12,y = 0)
    
    #事件处理函数
    def button1(event):
        #单击鼠标左键
        print("123")
        return 0
    
    
    #给空数组赋值(空数组赋值一定要用append函数,神器!)
    for i in range(81):
        button_list.append(tk.Button(window,text=shuzi,command = button1 ,font = f1,width=each_width_height,height=each_width_height//2))
    #摆放按钮位置
    for i in range(9):
        for j in range(9):
            button_list[(i * 9 + j)].place(x=j*90,y=i*90)#注意列表坐标顺序,xy颠倒了一下
    #对每一个按钮,都把鼠标左键单击事件(即<Button-1>)与自定义的事件处理函数button1绑定
    for i in range(9):
        for j in range(9):
            button_list[(i * 9 + j)].bind("<Button-1>",button1)
    
    
    # 进入消息循环
    window.mainloop()

    当我随便按一个button时,程序报错。

    原因是

    button_list[(i * 9 + j)].bind("<Button-1>",button1)

    button_list.append(tk.Button(window,text=shuzi,command = button1 ,font = f1,width=each_width_height,height=each_width_height//2))

    中的

    command = button1

    重复了(或者说冲突了)

    解决方法要么1要么2:

    方法1:去掉

    command = button1

    方法2:

    for i in range(9):
        for j in range(9):
            button_list[(i * 9 + j)].bind("<Button-1>",button1)

    这段代码去掉,然后还要把

    #事件处理函数
    def button1(event):
        #单击鼠标左键
        print("123")
        return 0

    括号里的参数event去掉(因为command = button1没有传递参数,所以event要删掉,否则会报错:“button1函数有一个参数,但实际接收了0个”)

    很明显,方法2无法传递event,也就是说事件处理函数就不能判断发生的事件的种类了。

  • 相关阅读:
    avaya电话重置
    Zscaler Client Connector
    tcpdump port 514
    rsyslog和过滤规则
    syslog,rsyslog和syslog-ng
    Ubuntu 搭建Rsyslog服务器
    syslog日志的类型和级别
    springboot_springSecurity整合
    springboot_整合JDBC_Druid数据源_MyBatis
    springboot_数据增删改查
  • 原文地址:https://www.cnblogs.com/ljfl-study/p/12402664.html
Copyright © 2020-2023  润新知