尽管没有按下键,为什么仍会调用绑定到绑定键的功能?

时间:2018-09-30 17:31:31

标签: python-3.x tkinter bind

好的,所以基本上,我正在尝试使用python3和工具箱界面创建登录系统。我希望在用户按下Enter键之后“发送”数据。但是,由于某种原因,在运行代码时(它是从下面未包含的单独的main.py文件中运行的,但这是一个简单的函数调用,我非常怀疑这是错误的来源),enterPressed函数是无需按任何键即可调用。由于运行时输入框中没有任何内容,因此会导致显示错误,这很烦人。为什么要调用该函数?如何防止在按下回车/返回键之前调用该函数?如果有帮助,我正在使用python3.6.6在最新版本的Ubuntu(18.04)上运行代码。

代码如下:

#___________________________________________________________
#Last Updated by _________ on September 30, 2018
#V1.0.0
#mainWindow.py

#Import tkinter to create the GUI:
from tkinter import *
#For creating message boxes:
import tkinter.messagebox as popup

#Import any other necessary, non-specific modules:
import pickle , os


#Declare all of the global variables:
firstRun = True

#KEY: windowAttsList = [window title , window resolution , make window fullscreen , remove toolbar , stop alt + f4 from working , window background color , main heading text , main heading background color , main heading foreground color , main heading typeface , main heading font size , id prompt text , id prompt background color , id prompt foreground color , id prompt typeface , id prompt font size , entry box input length , entry box typeface entry box font size , entry box background color , entry box foreground color , hide entry , allow changing input hiding setting , button background color , button foreground color , button active background color , button active foreground color]
#Default Values:
windowAttsList = ['___ Sign In' , '1080x720' , False , False , False , '#000000' , 'BHS Library Sign In' , '#000000' , '#FF5000' , 'Times New Roman' , 70 , 'Please Enter Your Student I.D. Below:' , '#000000' , '#FFFFFF' , 'Times New Roman' , 25 , 4 , 'Times New Roman' , 250 , '#FFFFFF' , '#000000' , True , True , '#0061FF' , '#FFFFFF' , '#FF5000' , '#000000']


#Updates all of the design variables for the window:
def updateWindowAtts(save = False , newAttsToSave = []):
    global windowAttsList

    #Check for a custom design file; if none exists, create one with the default values:
    if (not(os.path.exists('Data'))):
        os.mkdir('Data')

    if (save):
        with open('Data/mainWindowAtts.dat' , 'wb') as windowAttsFile:
            pickle.dump(newAttsToSave , windowAttsFile)
        return 0

    if (not(os.path.isfile('Data/mainWindowAtts.dat'))):
        #Use a with statement to ensure that the file automatically gets closed, even if an exception is thrown:
        with open('Data/mainWindowAtts.dat' , 'wb') as windowAttsFile:
            pickle.dump(windowAttsList , windowAttsFile)

    with open('Data/mainWindowAtts.dat' , 'rb') as windowAttsFile:
        windowAttsList = pickle.load(windowAttsFile)


#Define a function to enable/disable the private mode feature, that obscures the input:
def enablePrivateMode(box):
    if (windowAttsList[21]):
        box.configure(show = '')
    else:
        box.configure(show = '*')


#Define a function to be called once the enter key is pressed:

尽管没有按下任何键,但是一旦调用startWindow()函数,就会立即调用此函数:

def enterPressed(enteredDataSource):
    enteredData = enteredDataSource.get()

    try:
        enteredData = int(enteredData)
    except:

这是我运行代码后立即显示的错误消息;之所以触发,是因为enterDataSource.get()返回一个空字符串,因为尚未输入任何数据。

        popup.showerror('Invalid Input' , 'Error\nThe Input You Have Entered Is Not Valid.\nPlease Make Sure You Are Entering Only Integers.')
        return [False]

    if (len(enteredData) != (windowAttsList[16])):
        popup.showerror('Invalid Input' , 'Error\nThe Input You Have Entered Is Not Valid.\nPlease Make Sure The Length Of Your Input Is ' + str(windowAttsList[16]) + ' Integers.')
        return [False]

    return [True , enteredData]


#Creates and launches the GUI:
def startWindow():
    #If this is the first run, force an attributes check and update:
    global firstRun
    if (firstRun):
        updateWindowAtts()
        firstRun = False

    #Create the GUI window object:
    window = Tk()

    #Title the window:
    window.title(windowAttsList[0])

    #Determine the specific size of the window:
    window.geometry(windowAttsList[1])

    #Make the window fullscreen:
    if (windowAttsList[2]):
        window.attributes('-fullscreen', True)

    #Disable/Remove the toolbar, allowing for window closing, resizing, minimizing, etc.:
    if (windowAttsList[3]):
        window.overrideredirect(True)

    #Stop alt + f4 from working to close the window:
    if (windowAttsList[4]):
        window.protocol('WM_DELETE_WINDOW', passRequest)

    #Set the window background color:
    window.configure(bg = windowAttsList[5])

    #Create and pack a heading to display the title of the program:
    heading1 = Label(window , text = windowAttsList[6] , bg = windowAttsList[7] , fg = windowAttsList[8] , font = (windowAttsList[9] , windowAttsList[10]))
    heading1.pack(side = 'top' , pady = 10)

    #Add a text label asking for input:
    enterIDLabel = Label(window , text = windowAttsList[11] , bg = windowAttsList[12] , fg = windowAttsList[13] , font = (windowAttsList[14] , windowAttsList[15]))
    enterIDLabel.pack(side = 'top' , pady = 10)

    #Add an input box to enter the student I.D. number into:
    studentIDBox = Entry(window , width = windowAttsList[16] , font = (windowAttsList[17] , windowAttsList[18]) , bg = windowAttsList[19] , fg = windowAttsList[20])
    if (windowAttsList[21]):
        studentIDBox.configure(show = '*')
    else:
        studentIDBox.configure(show = '')
    studentIDBox.pack(side = 'top' , pady = 125)
    #Make the box automatically selected, and ready for text entry:
    studentIDBox.focus_set()

    #Add a button allowing for switching in and out of private mode:
    if (windowAttsList[22]):
        if (windowAttsList[21]):
            privateModeButtonText = 'Show Input'
        else:
            privateModeButtonText = 'Hide Input'
        privateModeButton = Button(window , text = privateModeButtonText , bd = 0 , bg = windowAttsList[23] , fg = windowAttsList[24] , activebackground = windowAttsList[25] , activeforeground = windowAttsList[26] , command = lambda: enablePrivateMode(studentIDBox))
        privateModeButton.place(x = 0 , y = 0)

    #Bind the return key, so that when it is pressed, the appropriate function will be called:

这是绑定键的地方:

    window.bind('<Return>' , enterPressed(studentIDBox))
    window.bind('<KP_Enter>' , enterPressed(studentIDBox))



    #Run the event listener main window loop:
    window.mainloop()

P.S。如果技术上不正确或不正确,请随时更正注释中使用的任何术语。我知道我可能不正确地使用了一些术语,并且我总是感谢建设性的批评。 :)

0 个答案:

没有答案