更改Tkinter

时间:2016-01-04 20:54:09

标签: python python-2.7 tkinter

我正在进行的程序允许用户输入文本并检查它是否是回文。输入按order()排序,使用testPalindrome(orderedText)测试,然后使用showResult(Palindrome)显示结果。在保存回文时我的问题出现了。如果用户已经被验证为回文,则该用户应该能够保存输入。我认为如果禁用保存按钮直到输入测试为真,那将是有意义的。所以我把" saveButton.config(state =' normal')"在showResult(Palindrome),但这不起作用。该错误表示"全局名称' saveButton'没有定义",我可以看到原因。但是,我无法做到正确。我想知道是否有可能通过对这一行文本的一些补充来解决这个问题,或者我是否需要进行更彻底的修改。 (例如,我尝试将" saveButton"转换为全局变量,例如" inputEntry"但无论出于何种原因,我都无法使其工作。)

    import Tkinter

    root = Tkinter.Tk()
    infoLabel = Tkinter.Label(root, text = 'Enter a text and check if it is a palindrome.', height = 12, width = 64, bg = 'green')
    inputEntry = Tkinter.Entry(root, width = 64)

    def main():
        window()
        Tkinter.mainloop()

    def window():
        root.title('Palindrome detector')
        root.geometry('534x285+500+250')
        infoLabel.grid(row = 0, rowspan = 1, column = 0, columnspan = 4, pady = 8, padx = 8)
        inputEntry.insert(0, 'Enter text...')
        inputEntry.grid(row = 1, rowspan = 1, column = 0, columnspan = 4, padx = 4)
        verifyButton = Tkinter.Button(root, text = 'Verify', width = 7, command = order).grid(row = 2, column = 0, pady = 10)
        saveButton = Tkinter.Button(root, text = 'Save', state = 'disabled', width = 7, command = save).grid(row = 2, column = 3)

    def order():
        Text_input = inputEntry.get()
        orderedText = Text_input.replace(" ", "")
        orderedText = orderedText.lower()
        orderedText = filter(str.isalnum, orderedText)
        if any(char.isalpha() or char.isdigit() for char in orderedText):
            testPalindrome(orderedText)
        else:
            infoLabel.config(text = 'The input must contain at least one alphanumeric character.', bg = 'red')

    def testPalindrome(orderedText):
        Palindrome = True
        i = 0
        for char in orderedText:
            if orderedText[i] == orderedText[-(i+1)]:
                Palindrome = True
                i += 1
            else:
                Palindrome = False
                break
        showResult(Palindrome)

    def showResult(Palindrome):
        if Palindrome == True:
            infoLabel.config(text = 'Yes! "' + str(inputEntry.get()) + '" is a palindrome!', bg = 'green')
            saveButton.config(state = 'normal')
        else:
            infoLabel.config(text = 'No! "' + str(inputEntry.get()) + '" is not a palindrome!', bg = 'red')
            saveButton.config(state = 'disabled')

    def save():
        savePalindrome = inputEntry.get()
        palindromes_file = open("Palindromes.txt", "a")
        palindromes_file.write(savePalindrome + "\n")
        palindromes_file.close()
        infoLabel.config(text = '"' + str(savePalindrome) + '" has been saved to file.', bg = 'green')
        saveButton.config(state = 'disabled')

    if __name__ == '__main__':
        main()

编辑:看完答案后,我跟着一本教科书,试图用课程重写整个事情。当然,可能会有任何数量的缺陷。我现在关心的是#34; NameError:全球名称' testPalindrome'未定义"。该错误按顺序(第7行)进行。我不明白为什么这条线和#34;桥#34;在order(self)和testPalindrome(self)之间突然出现了问题?

    import Tkinter
    import tkMessageBox

    root = Tkinter.Tk()

    class MyGUI:
        def __init__(self, master):
            self.master = master
            master.title('Palindrome detector')
            master.geometry('534x285+500+250')
            self.infoLabel = Tkinter.Label(self.master, text = 'Enter a text and check if it is a palindrome.', height = 12, width = 64, bg = 'green')
            self.inputEntry = Tkinter.Entry(self.master, width = 64)
            self.infoLabel.grid(row = 0, rowspan = 1, column = 0, columnspan = 4, pady = 8, padx = 8)
            self.inputEntry.insert(0, 'Enter text...')
            self.inputEntry.grid(row = 1, rowspan = 1, column = 0, columnspan = 4, padx = 4)
            self.verifyButton = Tkinter.Button(self.master, text = 'Verify', width = 7, command = self.order)
            self.verifyButton.grid(row = 2, column = 0, pady = 10)
            self.saveButton = Tkinter.Button(self.master, text = 'Save', state = 'disabled', width = 7, command = self.save)
            self.saveButton.grid(row = 2, column = 3)

        def order(self):
            self.Text_input = self.inputEntry.get()
            self.orderedText = self.Text_input.replace(" ", "")
            self.orderedText = self.orderedText.lower()
            self.orderedText = filter(str.isalnum, self.orderedText)
            if any(char.isalpha() or char.isdigit() for char in self.orderedText):
                testPalindrome(self)
            else:
                self.infoLabel.config(text = 'The input must contain at least one alphanumeric character.', bg = 'red')

        def testPalindrome(self):
            self.Palindrome = True
            i = 0
            for char in self.orderedText:
                if self.orderedText[i] == self.orderedText[-(i+1)]:
                    self.Palindrome = True
                    i += 1
                else:
                    self.Palindrome = False
                    break
            showResult(self)

        def showResult(self):
            if self.Palindrome == True:
                self.infoLabel.config(text = 'Yes! "' + str(self.inputEntry.get()) + '" is a palindrome!', bg = 'green')
                self.saveButton.config(state = 'normal')
            else:
                self.infoLabel.config(text = 'No! "' + str(self.inputEntry.get()) + '" is not a palindrome!', bg = 'red')
                self.saveButton.config(state = 'disabled')

        def save(self):
            self.savePalindrome = self.inputEntry.get()
            self.palindromes_file = open("Palindromes.txt", "a")
            self.palindromes_file.write(self.savePalindrome + "\n")
            self.palindromes_file.close()
            self.infoLabel.config(text = '"' + str(self.savePalindrome) + '" has been saved to file.', bg = 'green')
            self.saveButton.config(state = 'disabled')

    my_gui = MyGUI(root)
    Tkinter.mainloop()

2 个答案:

答案 0 :(得分:2)

您在函数中创建saveButton因此它是局部变量,并且在其他函数中不可用。您可以使用global saveButton中的window()将此变量设为全局变量。

def window():
    global saveButton

    # ....

    saveButton = Tkinter.Button(...)
    saveButton.grid(...)

-

正如凯文已经说过的那样:

这一行

 saveButton = Tkinter.Button(...).grid(...)

None分配给saveButton因为grid()始终返回None

使用

 saveButton = Tkinter.Button(...)
 saveButton.grid(...)

 Tkinter.Button(...).grid(...)

如果您不需要saveButton变量。

答案 1 :(得分:0)

只需将调用放入验证功能,因为您希望每次它都是Palindrome时自动保存。并且您可以将值传递给函数,而不是第二次获取它。

def testPalindrome(orderedText):
    ## change to False so an empty string will not 
    ## register as True
    Palindrome = False
    i = 0
    for char in orderedText:
        if orderedText[i] == orderedText[-(i+1)]:
            Palindrome = True
            i += 1
        else:
            Palindrome = False
            break
    showResult(Palindrome)
    if Palindrome:
        save(orderedText)

接下来学习课程,因为它解决了这些问题。网络上的许多教程之一http://python-textbok.readthedocs.org/en/latest/Introduction_to_GUI_Programming.html要使按钮全局化,请将其放在全局命名空间中(如inputEntry)。

root = Tkinter.Tk()
infoLabel = Tkinter.Label(root, text = 'Enter a text and check if it is a palindrome.', height = 12, width = 64, bg = 'green')
inputEntry = Tkinter.Entry(root, width = 64)

saveButton = Tkinter.Button(root, text = 'Save', state = 'disabled', width = 7, command = save)
saveButton.grid(row = 2, column = 3)