循环时tkinter对话框窗口无法正常工作?

时间:2016-08-30 15:18:26

标签: python-3.x tkinter while-loop menu

显然,tkinter不允许你使用while循环,因为它已经运行了自己的循环所以我需要帮助才能使我的代码与while循环一起工作。我相信它与" mainloop()"有关。但我不确定如何使用它。

下面的代码(无循环工作):

while (1):
    choice = input("Choose 1 to open dialog, 2 to end the program.\n")
    if choice == "1":
        from tkinter import *
        root = Tk()
        root.withdraw()
        fileName = filedialog.askopenfilename(filetypes = ([("Text file","*.txt")]),title='Please select a text file')
        file = open(fileName)
        sentence = file.read()
        file.close()

    elif choice == "2":
        break

1 个答案:

答案 0 :(得分:0)

一旦你用root.witdraw()拉开了窗口,所有与root相关联的代码都将无法运行,因此你需要在用户打开对话框时保持窗口打开

你可以在窗口贴上label说“选择一些对话框打开”,或者正如Bryan Oakley所说,你可以使用命令行或图形界面

choice = ""
while choice != "2": # no need for brackets here
    choice = input("Choose 1 to open dialog, 2 to end the program.\n")
    if choice == "1":
        from tkinter import *
        root = Tk()
        root.title("Choose dialog")
        #root.withdraw() this causes the problem
        fileName = filedialog.askopenfilename(filetypes = ([("Text file","*.txt")]),title='Please select a text file')
        if fileName != "": # if they choose not to open a file
            file = open(fileName)
            sentence = file.read()
            print(sentence)
            file.close()
            root.destroy() # destroys the window

我已经对它进行了测试,这确实有效,希望这有助于你