【问题标题】:Tkinter one button changes 2 entriesTkinter 一键更改 2 个条目
【发布时间】:2017-02-16 07:39:14
【问题描述】:

我正在使用具有两个浏览按钮的 Tkinter 构建一个简单的应用程序。一个需要能够以文件为目标,而另一个只需要一个文件夹。这可行,但是当我使用任一按钮浏览时,它会填充两个条目。我是 Tkinter 的新手,所以我不太明白为什么。

我正在使用这个问题的代码: How to Show File Path with Browse Button in Python / Tkinter

这是我的浏览功能:

def open_file(type):
global content
global file_path
global full_path

if type == "file":
    filename = askopenfilename()
    infile = open(filename, 'r')
    content = infile.read()
    file_path = os.path.dirname(filename)
    entry.delete(0, END)
    entry.insert(0, file_path+filename)
    return content

elif type == "path":
    full_path = askdirectory()
    entry2.delete(0, END)
    entry2.insert(0, full_path)
    #return content

这是我的 GUI 代码:

mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250)
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250)
f2.pack(fill=X)

Label(f1, text="Select Your File (Only txt files)").grid(row=0, column=0, sticky='e')
Label(f2, text="Select target folder").grid(row=0, column=0, sticky='e')
entry = Entry(f1, width=50, textvariable=file_path)
entry2 = Entry(f2, width=50, textvariable=full_path)
entry.grid(row=0, column=1, padx=2, pady=2, sticky='we', columnspan=25)
entry2.grid(row=0, column=1, padx=(67, 2), pady=2, sticky='we', columnspan=25)
Button(f1, text="Browse", command=lambda: open_file("file")).grid(row=0, column=27, sticky='ew', padx=8, pady=4)
Button(f2, text="Browse", command=lambda: open_file("path")).grid(row=0, column=27, sticky='ew', padx=8, pady=4)

我该如何解决这个问题?谢谢

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    注意 full_path(open_file 方法中的局部变量)与全局变量同名。

    您应该将 StringVar 用于文本变量。

    更改file_pathfull_path 的初始化

    global file_path
    global full_path
    file_path = StringVar()
    full_path = StringVar()
    

    而不是那些行:

    entry.delete(0, END)
    entry.insert(0, file_path+filename)
    

    你可以简单地写:

    full_path.set(file_path+filename)
    

    entry2 相同,而不是:

    elif type == "path":
        full_path = askdirectory()
        entry2.delete(0, END)
        entry2.insert(0, full_path)
    

    写:

    elif type == "path":
        full_path_dir = askdirectory()
        full_path.set(full_path_dir)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      相关资源
      最近更新 更多