【问题标题】:How can I assign the text imputed into an entry box (tkinter) to variable in python script and run the script by pressing a button?如何将输入框(tkinter)中的文本分配给python脚本中的变量并通过按下按钮运行脚本?
【发布时间】:2021-07-08 21:00:24
【问题描述】:

我有一个 python 脚本,它采用文件路径并运行以下脚本:

    file = 'C:/Users/crist/Downloads/Fraction_Event_Report_Wednesday_June_16_2021_20_27_38.pdf'
    
    lines = []
    with pdfplumber.open(file) as pdf:
        pages = pdf.pages
        for page in pdf.pages:
            text = page.extract_text()
            print(text)

我用 tkinter 创建了一个输入框:

     import tkinter as tk

master = tk.Tk()
tk.Label(master, 
         text="File_path").grid(row=0)

e = tk.Entry(master)


e.grid(row=0, column=1)


tk.Button(master, 
          text='Run Script', 
          command=master.quit).grid(row=3, 
                                    column=0, 
                                    sticky=tk.W, 
                                    pady=4)

tk.mainloop()

我想将用户在输入框中输入的 File_path 分配给脚本中的“文件”,并在按下“运行脚本”按钮时运行脚本。我该怎么做?

【问题讨论】:

  • 改成函数使用e.get().

标签: python tkinter jupyter-notebook tkinter-entry


【解决方案1】:

最好生成一个文件对话框而不是使用tkinter.Entry

# GUI.py
from tkinter.filedialog import askopenfilename
import tkinter as tk

# Create the window and hide it
root = tk.Tk()
root.withdraw()

# Now you are free to popup any dialog that you need
filetypes = (("PDF file", "*.pdf"), ("All files", "*.*"))
filepath = askopenfilename(filetypes=filetypes)

# Now use the filepath
lines = []
with pdfplumber.open(filepath) as pdf:
    ...

# Destroy the window
root.destroy()

【讨论】:

  • 你能帮我理解一下代码吗?那么从弹出窗口中选择pdf文件后,我应该复制文件路径并将其插入输入框中吗?
  • @Cristian 为什么不在你的其他函数中使用它(在with pdfplumber.open(file) as pdf 中使用它的函数)?这将绕过条目的需要。
  • @Cristian 我误解了这个问题吗?据我了解,您希望在另一个脚本(处理.pdf 的脚本)中获取用户选择的文件。
  • 哦,有道理。虽然 idk 如何做到这一点......所以在使用您提供的代码选择文件后,我将如何从 pdfplumber.open(file) 函数中将路径分配给“文件”? @TheLizzard
  • 我希望用户选择他们的文件,然后将该文件用于我的 pfdplumber 函数并为所选的 pdf 运行脚本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
  • 2018-01-28
  • 2021-06-09
  • 2016-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多