我正在使用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()
这是我的主要代码的功能;我的主tkinter窗口上有一个按钮,它具有运行此功能的命令。 connect databaseEntry函数在一个名为scripts的文件夹中构成另一个名为databaseManip的文件,我使用它来导入:
from scripts.databaseManip import connectDatabase
并且该文件中的代码是:
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'
我已经找到了一个答案,但似乎没有什么是lambda所以我迷路了。什么是代码?
答案 0 :(得分:1)
&
没有按照您的想法行事。它找到两个对象的按位and
。相反,尝试定义函数:
def function():
connectDatabase(databaseEntry.get())
cManip.destroy()
entrySubmit = ttk.Button(cManip, text="Enter", width=20, command=function)
您还可以将&
替换为and
,如果第一个函数调用始终只返回None
(或其他虚假值),则该函数将起作用,但这是一种令人讨厌的,愚蠢的,聪明的,不可读的方式来做你想做的事情,并且可能会导致你和任何阅读你代码的人感到困惑。