Python3.7从Entry得到的值在get()之后返回为空

本人新手,目的是为了点击“浏览”选择需要打开的文件夹,然后将文件夹路径显示在文本框中,并把这个路径赋值给openpath,因为以后的其他函数会用到这个路径。但是现在返回的是空值,请大神释疑,谢谢。


import tkinter as tk
import os
from tkinter import filedialog

def getopendir():
    global open_dir1
    open_dir1 = filedialog.askdirectory()
    open_dir2.set(open_dir1)

windows = tk.Tk()

open_dir2 = tk.StringVar()

# 生成对话框
windows.title("小工具")
windows.geometry("950x600+400+200")

# 生成需要压缩的文件夹标题
open_label = tk.Label(windows, text="选择需要压缩的文件夹:")
open_label.place(x=10, y=20)

# 定义需要压缩的文件夹输入框
open_dir = tk.Entry(windows, textvariable=open_dir2)
open_dir.place(x=10, y=50, width=800, height=40)

# 生成浏览文件夹的按钮
scanopen_btn = tk.Button(windows, text="浏览", command=getopendir)
scanopen_btn.place(x=820, y=50, width=120, height=40)

openpath = open_dir.get()
print('openpath:', openpath)

windows.mainloop()

改成这样试试!

import tkinter as tk
import os
from tkinter import filedialog

def getopendir():
    global open_dir1
    open_dir1 = filedialog.askdirectory()
    open_dir2.set(open_dir1)

windows = tk.Tk()

open_dir2 = tk.StringVar()

windows.title("小工具")
windows.geometry("950x600+400+200")

# 生成需要压缩的文件夹标题
open_label = tk.Label(windows, text="选择需要压缩的文件夹:")
open_label.place(x=10, y=20)

# 定义需要压缩的文件夹输入框
open_dir = tk.Entry(windows, textvariable=open_dir2)
open_dir.place(x=10, y=50, width=800, height=40)

# 生成浏览文件夹的按钮
scanopen_btn = tk.Button(windows, text="浏览", command=getopendir)
scanopen_btn.place(x=820, y=50, width=120, height=40)

windows.mainloop()

openpath = open_dir2.get()
print('openpath:', openpath)

输入一条路径,之后退出!

label内还要更新一下

你这返回空值是因为,你的代码一运行就打印出来的,并不是你选择文件夹路径之后打印的,如果你想得到选择的路径,就必须等待文件夹选择操作完成之后才行

import tkinter as tk
import os
from tkinter import filedialog

def getopendir():
    global open_dir1
    open_dir1 = filedialog.askdirectory()
    open_dir2.set(open_dir1)
    #文件夹路径
    openpath = open_dir1
    print('openpath:', openpath)

windows = tk.Tk()

open_dir2 = tk.StringVar()

# 生成对话框
windows.title("小工具")
windows.geometry("950x600+400+200")

# 生成需要压缩的文件夹标题
open_label = tk.Label(windows, text="选择需要压缩的文件夹:")
open_label.place(x=10, y=20)

# 定义需要压缩的文件夹输入框
open_dir = tk.Entry(windows, textvariable=open_dir2)
open_dir.place(x=10, y=50, width=800, height=40)


# 生成浏览文件夹的按钮
scanopen_btn = tk.Button(windows, text="浏览", command=getopendir)
scanopen_btn.place(x=820, y=50, width=120, height=40)


windows.mainloop()