Python:使用lambd时,&:“NoneType”和“NoneType”不支持操作数类型

2024-09-30 08:36:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用lambda来制作一个tkinter按钮,在两个按钮之间执行两个操作:

def classManip():    
    cManip = tk.Toplevel()
    cManip.title('Class Manipulator')
    cManip.minsize(400,100)
    cManip.maxsize(400,100)

    databaseEntry = ttk.Entry(cManip, width = 25)
    databaseEntry.place(relx = .5, rely = .375, anchor = "c")

    entrySubmit = ttk.Button(cManip, text = "Enter", width = 20, command = lambda : connectDatabase(databaseEntry.get()) & cManip.destroy())
    entrySubmit.place(relx = .5, rely = .625, anchor="c")
    cManip.mainloop()

这是我的主代码中的函数;我的主窗口上有一个按钮,上面有运行这个函数的命令。 connect databaseEntry函数在名为scripts的文件夹中形成另一个名为databaseManip的文件,我使用以下方法导入:

^{pr2}$

文件中的代码是:

import sqlite3, sys, os
import tkinter as tk
from win32api import GetSystemMetrics

#connects or creates database
def connectDatabase(name):
    name = str(name)
    screenWidth =  GetSystemMetrics (0)
    screenHeight =  GetSystemMetrics (1)

    if os.path.isfile("classDbFiles/" + name + ".db"):
        conn = sqlite3.connect("classDbFiles/" + name + ".db")
        tk.messagebox.showinfo(message="Connected to %s successfully" % (str(name + ".db")), title = "File Found")
    else:   
        conn = sqlite3.connect("classDbFiles/" + name + ".db")
        tk.messagebox.showinfo(message = "The database file %s was created and opened successfully" % (str(name + ".db")), title = "Success")

我想让程序做的是运行数据库函数,创建或打开.db文件,然后关闭tkinter窗口,有趣的是,它确实可以工作,但它返回错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "E:\Program Files\Python\lib\tkinter\__init__.py", line 1475, in __call__
    return self.func(*args)
  File "C:\Users\Patrick\Dropbox\Computing Project\mainApp.py", line 52, in <lambda>
    entrySubmit = ttk.Button(cManip, text = "Enter", width = 20, command = lambda : connectDatabase(databaseEntry.get()) & cManip.destroy())
TypeError: unsupported operand type(s) for &: 'NoneType' and 'NoneType'

我一直在寻找答案,但似乎没有什么适合兰姆达的,所以我迷路了。代码怎么了?在


Tags: lambda函数代码namedbtitletkinterwidth
1条回答
网友
1楼 · 发布于 2024-09-30 08:36:42

&没有做你认为的那样。它查找两个对象的按位and。相反,请尝试定义函数:

 def function():
     connectDatabase(databaseEntry.get())
     cManip.destroy()

 entrySubmit = ttk.Button(cManip, text="Enter", width=20, command=function)

您也可以将&替换为and,如果第一个函数调用始终只返回None(或另一个假值),,但这是一种令人讨厌的、老套的、聪明的、不可读的方法,很可能会导致您和任何阅读您的代码的人感到困惑。在

相关问题 更多 >

    热门问题