Winow.py 为窗体 从窗体选取文件夹项目地址保持窗体不关闭 传导 Run.py中 进行下一步运行

描述:

‘’’
Winow.py 为窗体 从窗体选取文件夹项目地址 传导 Run.py中 进行下一步运行
‘’’

Winow.py

import tkinter as tk
from tkinter import filedialog
import threading

def Wins():
global paH
paH = filedialog.askdirectory()
“””
paH 类型 <class ‘str’> “””
window = tk.Tk() # 窗体

max_w, max_h = window.maxsize()
window.geometry(f’500x300+{int((max_w - 500) / 2)}+{int((max_h - 300) / 2)}’) # 居中显示
window.resizable(width=False, height=False)
window.title(“文件夹选择”) # 窗口标题
window.tk.call(‘wm’, ‘iconphoto’, window._w, tk.PhotoImage(file=’eye.png’))

l = tk.Label(window,text=”请选择要监控的文件夹目录”,font=(“宋体”,15)).grid(row=0, column=0)

b = tk.Button(window, text=”选择文件”, command=Wins).grid(row=0, column=1)
window.mainloop()
‘’’
如何 窗体不结束的情况下 继续运行 run.py部分
‘’’

Run.py

from Winow import Wins

#tx = w.Windows()
print(“日志目录”)
print(paH.Wins)

#print(“地址”,tx)

‘’’
代码运行 报错
print(paH.Wins)
NameError: name ‘paH’ is not defined
‘’’
‘’’ 应该如何修改?谢谢😀’’’

讨论数量: 2
Jason990420

Some key points here

  • Basically, your GUI should work on the main thread and run your script on the sub thread.
  • Not to run the code in the import statement, but call the imported functions or imported classes in your main thread.
  • Access the information by the attribute of a class instance.

Example Code

# Window.py

import tkinter as tk
from tkinter import filedialog


class GUI():

    def __init__(self):
        self.window = tk.Tk()
        w1, h1 = (500, 300)
        w2, h2 = self.window.winfo_screenwidth(), self.window.winfo_screenheight()
        self.window.geometry(f'{w1}x{h1}+{(w2-w1)//2}+{(h2-h1)//2}')
        self.window.title("文件夹选择")
        self.window.resizable(width=False, height=False)
        self.icon_png = tk.PhotoImage(file='enemy.png')
        self.window.iconphoto(False, self.icon_png)
        self.label = tk.Label(self.window, text="请选择要监控的文件夹目录", font=("宋体", 15))
        self.label.grid(row=0, column=0)
        self.button = tk.Button(self.window, text="选择文件", command=self.askdirectory)
        self.button.grid(row=0, column=1)
        self.path = None
        self.running = False

    def askdirectory(self):
        self.path = filedialog.askdirectory()
        # print(repr(self.path))
# Run.py

from time import sleep
import threading
from Window import GUI

def func(gui):
     # Set it to False elsewhere if you need to break from the while loop
    gui.running = True
    """
    Waiting GUI to get the path of directory, 
    or your `func` will end before you select the directory.
    """
    while gui.running:
        if gui.path:
            break
        sleep(0.1)
    print(gui.path)     # Access the path by the attribute `path` of class GUI.
    gui.running = False

gui = GUI()             # GUI work on the main thread
threading.Thread(target=func, args=(gui,), daemon=True).start()

gui.window.mainloop()
1年前 评论

我已看到 你发的代码了 我现在看看 代码 什么意思 :+1:

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!