本文介绍了如何将askdirectory结果保存到我可以在OOP中使用tkinter的变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些麻烦.我是OOP的新手,通常使用tkinter和GUI.

I have ran into some trouble.I'm quite new to OOP and working with tkinter and GUI's in general.

我设法在Internet上找到了一些代码并将它们网格化在一起以创建某些东西,而我几乎要成为现实了.

I have managed to find some code on the Internet and meshed it all together to create something and I'm nearly where I want to be.

所以我想要一些帮助来解决这个问题.

So what I want is some help figuring this out.

如何将askdirectory的结果分配给可以在其他地方使用的变量?

How can I assign results of askdirectory to a variable I can use elsewhere?

# coding=utf-8
import tkinter as tk
from tkinter import font as tkfont
from tkinter import filedialog


class MainApp(tk.Tk):
    ....
class SelectFunction(tk.Frame):
    ....
class FunctionChangeName(tk.Frame):
    ....
        a = Gui(self)
        # this gets me the askdirectory but how to add it to a variable?

上面是运行askdirectory代码的调用,它起作用了,只需要找出如何将其保存到变量中就可以使用它,我已经尝试了几种打印方法,但是我得到了是.!frame.!functionchangename.!gui的东西.

Above is the call to run askdirectory code, and it works, just need to find out how to save it to a variable so I can use it, I have tried to print it in several ways, but all I get is something along the lines .!frame.!functionchangename.!gui.

class SelectDir:
    def __init__(self, container, title, initial):
        self.master = container

        self.initial = initial
        self.selected = initial

        self.options = {'parent': container,'title': title,'initialdir':initial,}

    def show(self):
        result = filedialog.askdirectory()
        if result:
            self.selected = result

    def get(self):
        return self.selected


class Gui(tk.Frame):

    def __init__(self, container):
        tk.Frame.__init__(self, container)

        frame = tk.Frame(container)
        frame.pack()

        self.seldir = SelectDir(self, "Select directory", "D:\\MyPgm\\Python\\Tiles_8")

        button = tk.Button(frame, text="Select directory", command=self.select_dir)
        button.grid(column=0, row=0)

        self.act_dir = tk.StringVar()
        self.act_dir.set("D:\\MyPgm\\Python\\Tiles_8")

        entry = tk.Entry(frame, textvariable=self.act_dir, width=30)
        entry.grid(column=0, row=1)

    def select_dir(self):
        self.seldir.show()
        self.act_dir.set(self.seldir.get())
        # or
        # result = seldir.show()
        # self.act_dir.set(result)

if __name__ == "__main__":
    app = MainApp()
    app.mainloop()

推荐答案

我有一个主意:

例如,如果函数中包含f,则可以将其作为变量进行全局访问

I had an idea:

example, if you have f inside a function, you can make it global to have access as variable

def print_path():  
    # select working directory
    global f #make f global to access the path
    f = filedialog.askdirectory(parent=root, initialdir="/", title='Select Dir') 

这篇关于如何将askdirectory结果保存到我可以在OOP中使用tkinter的变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 03:23