zoukankan      html  css  js  c++  java
  • [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,也就是说事件处理函数就不能判断发生的事件的种类了。

  • 相关阅读:
    windows下操作linux虚拟机映射网络驱动器中文件提示chmod权限不足解决方案
    Centos 更改MySQL5.7数据库目录位置
    MySQL语句增加字段,修改字段名,修改类型,修改默认值
    [MySQL]MySQL数据库中如何查询分组后每组中的最后一条记录?
    ROW_NUMBER()函数使用详解
    【转】mysql 存储过程的示例
    简简单单储存过程——循环一个select结果集
    mysql存储过程demo
    mysql日期加一个天数获得新的日期
    使用SyncNavigator轻松实现数据库异地同步、断点续传、异构同步
  • 原文地址:https://www.cnblogs.com/ljfl-study/p/12402664.html
Copyright © 2011-2022 走看看