对于这段代码,我的目的是添加一个函数来添加用户输入到数据库中的数据。我已经设置了一个函数来创建用户界面,让他们输入数据,还有一个函数来检索数据。但是,我收到一条错误消息,说DeliveryInterface变量尚未定义。有没有办法让add data函数从上一个函数中识别DeliveryInterface变量?我附加导致问题的代码段。你知道吗
def InputScreen():
DeliveryInterface = tkinter.Tk() #creates the interface for the input screen
DeliveryInterface.title('Input New Data') #gives the new window a title
DeliveryInterface.geometry('400x500') #sets the default size of the window as 400 x 500
DeliveryInterface.maxsize(400, 500) #sets the maximum size of the interface as 400 x 500
DeliveryInterface.configure(background='#0092FF') #sets the background colour of the inteface to the light blue as seen in the main menu interface
(.......)
StockIDLabel = tkinter.Label(DeliveryInterface, text='Stock ID', font=('Helvetica', 16)) # creates a label that tells the user that the next box is associated with the stock id
StockIDLabel.place(x=30, y=60, height=22, width=200)
StockID_entry = tkinter.Entry(DeliveryInterface, font=('Helvetica', 16)) # creates the entry box for the stock ID
StockID_entry.place(x=250, y=60, height=22, width=100)
(...........)
def addingNewStock():
StockID = 0 #Initialises the stock ID
StockID = DeliveryInterface.StockID_entry.get() #intended to get the data from the entrybox, however, i get an error message say that DeliveryInterface hasnt been defined
print (StockID) #prints the stockID so that i now if the variable has been changed.
我希望这是所有需要的信息,谢谢
必须使
DeliveryInterface
全局:另一个选择是使用python3的
nonlocal
关键字。你知道吗您所面临的问题是变量有其作用域-您已将DeliveryInterface定义为存在于InputScreen()中-而它不会存在于其他任何地方。你知道吗
您可以选择以下几种方法来解决此问题:
使其成为全局变量。这通常是不赞成的,被认为是一个坏的做法,但仍然可以是合理的。你知道吗
使InputScreen成为一个类,该类将具有初始化和添加新库存的方法。通过这样做,类将记住它的状态——变量的值。你知道吗
或者将DeliveryInterface作为参数传递给addingNewStock()函数。如果您正从函数InputScreen()调用此函数,那么这将是最简单的解决方案。你知道吗
相关问题 更多 >
编程相关推荐