用于打开文件的Python3和tkinter GUI按钮

时间:2016-12-06 18:06:47

标签: python python-3.x user-interface tkinter

我创建了一个程序,它使用PIL检查图像并返回大小,颜色数量,dpi等,但现在我想将我的代码放入GUI系统来帮助用户。

我在函数中使用了askopenfilename(),但在尝试打开新文件时遇到了问题。我在程序启动后运行该功能,它让我选择一个文件并且工作得很好。当我单击按钮打开新文件时,它允许我选择一个新文件,但它不会更改任何显示的信息。

如何在选择新文件后使用新信息刷新屏幕?这是我的代码:

def openPattern():
    global fileName
    path = askopenfilename()
    fileOpen = open(path, 'r')
    fileName = os.path.basename(path)

if __name__ == '__main__':
    root = Tk()
    root.title("Art Intake | Developer Build")
    ms = MainScreen(root)
    ms.config(bg="grey")

    openPattern()
    pattern = Button(ms, text="Choose a file", command=openPattern,   
                highlightbackground='grey')
    pattern.pack()
    pName = Label(ms, text="Pattern Name: " + str(fileName), 
                 bg='grey')
    pName.pack()

    read = Button(ms, text="ReadMe", command=openRM, 
              highlightbackground='grey')
    read.place(rely=1.0, relx=1.0, x=-25, y=-15, anchor=SE)

    quit = Button(ms, text="Quit", command=ms.quit, 
             highlightbackground='grey')
    quit.place(rely=1.0, relx=1.0, x=-25, y=-45, anchor=SE)

root.mainloop()

1 个答案:

答案 0 :(得分:0)

开始时,在创建标签openPattern()之前运行pName并显示标签fileName。但是稍后你必须手动更改标签中的文字。

    pName['text'] = "Pattern Name: " + fileName

首先我创建空标签,然后运行openPattern(),以便更新现有标签中的文本。当我单击按钮时,openPattern()执行相同操作 - 它会更新现有标签中的文本。

(未经测试,因为代码不完整)

def openPattern():
    path = askopenfilename()
    fileOpen = open(path, 'r')
    fileName = os.path.basename(path)

    pName['text'] = "Pattern Name: " + fileName

if __name__ == '__main__':
    root = Tk()
    root.title("Art Intake | Developer Build")

    ms = MainScreen(root)
    ms.config(bg="grey")

    pattern = Button(ms, text="Choose a file", command=openPattern,   
                highlightbackground='grey')
    pattern.pack()
    pName = Label(ms, bg='grey')
    pName.pack()

    read = Button(ms, text="ReadMe", command=openRM, 
              highlightbackground='grey')
    read.place(rely=1.0, relx=1.0, x=-25, y=-15, anchor=SE)

    quit = Button(ms, text="Quit", command=ms.quit, 
             highlightbackground='grey')
    quit.place(rely=1.0, relx=1.0, x=-25, y=-45, anchor=SE)

    openPattern()

    root.mainloop()