Как получить значение из команды tkinter - PullRequest
0 голосов
/ 24 января 2019

Возможно, это вопрос новичка, но у меня возникают проблемы с выяснением того, как получить значение из функции, которая будет использоваться в качестве входных данных для другой.Я также хотел бы получить несколько советов по организации кода.В этом примере я пытаюсь получить путь к папке filePath и outPut для использования в функции processFile.

Спасибо

Код:

    from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader

version = "v0.0.01"


root = Tk()



def window (main):

    main.title("File Opener " + version)
    width = main.winfo_width()
    main.geometry('500x200')

numero = str(1)

def OpenFile():
    fileName = askopenfilename(initialdir="C:/",
                            filetypes =(("PDF File", "*.pdf"),("All Files","*.*")),
                            title = "Select PDF File",
                           )

    labelName = Label(text="File Path: " + fileName)
    labelName.pack()
    print(fileName)
    return fileName

def outputFolder():                                         #Bug, label keeps adding paths
    outPath = askdirectory()

    labelName2 = Label(text="Output Folder: " + outPath)
    labelName2.pack()
    print(outPath)
    return outPath



def processFile(inFile,outFolder):

   ''' print(fileName) get input name and output variables
    print(outPath)'''




label = ttk.Label(root, text ="",foreground="black",font=("Helvetica", 16))
label.pack()


#Button Open-----------

button1 = Button (text = "Open File", command = OpenFile)
button1.pack()


#Button Start---------
buttonStart = Button (text = "Start Process", command = processFile)#give as parameter inputFile and link
buttonStart.place(height=50, width=100)

#Button Open-----------

button3 = Button (text = "Output Folder", command = outputFolder)
button3.pack()


#Menu Bar ----------------

menu = Menu(root)
root.config(menu=menu)

file = Menu(menu)


file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())

menu.add_cascade(label = 'File', menu = file)


window(root)
root.mainloop()

Ответы [ 3 ]

0 голосов
/ 24 января 2019
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader

version = "v0.0.01"


root = Tk()




def window (main):

    main.title("File Opener " + version)
    width = main.winfo_width()
    main.geometry('500x200')
    main.configure(background = 'black')

numero = str(1)

#openFile
def OpenFile():
    global fileName
    fileName = askopenfilename(initialdir="C:/",
                            filetypes =(("PDF File", "*.pdf"),("All Files","*.*")),
                            title = "Select PDF File",
                           )

    labelName = Label(text="File Path: " + fileName)
    labelName.pack()
    print(fileName)
    return str(fileName)

#getOutputPath

def outputFolder():                                         #Bug, label keeps adding paths
    outPath = askdirectory()

    labelName2 = Label(text="Output Folder: " + outPath)
    labelName2.pack()
    print(outPath)
    return outPath

#testFunct

def printFilename(inArg):
    print(inArg)
    x = OpenFile()
    print (OpenFile())




lambda: printFilename(fileName)

#processRealDeal

def processFile(): #THIS IS THE MAIN FUNC

   ''' print(fileName) get input name and output variables
    print(outPath)'''


print (OpenFile)

label = ttk.Label(root, text ="",foreground="black",font=("Helvetica", 16))
label.pack()


#Button Open-----------

button1 = Button (text = "Open File", command = OpenFile)
button1.pack()


#Button Start---------
buttonStart = Button (text = "Start Process", command = lambda: printFilename("Hello World!!!"))#give as parameter inputFile and link
buttonStart.place(height=50, width=100)

#Button Open-----------

button3 = Button (text = "Output Folder", command = outputFolder)
button3.pack()


#Menu Bar ----------------

menu = Menu(root)
root.config(menu=menu)

file = Menu(menu)


file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())

menu.add_cascade(label = 'File', menu = file)


window(root)
root.mainloop()
0 голосов
/ 24 января 2019

Не вижу, чтобы вы объявили глобальную переменную fileName вне функции.

Я сделал это

from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader

version = "v0.0.01"


root = Tk()


fileName = "test"

def window (main):

    main.title("File Opener " + version)
    width = main.winfo_width()
    main.geometry('500x200')
    main.configure(background = 'black')

numero = str(1)

#openFile
def OpenFile():
    global fileName
    fileName = askopenfilename(initialdir="C:/",
                            filetypes =(("PDF File", "*.pdf"),("All Files","*.*")),
                            title = "Select PDF File",
                           )

    labelName = Label(text="File Path: " + fileName)
    labelName.pack()
    test()
    return str(fileName)

#getOutputPath

def test():
    print(fileName)

def outputFolder():                                         #Bug, label keeps adding paths
    outPath = askdirectory()

    labelName2 = Label(text="Output Folder: " + outPath)
    labelName2.pack()
    print(outPath)
    return outPath

#testFunct

def printFilename(inArg):
    print(inArg)
    x = OpenFile()
    print (OpenFile())




lambda: printFilename(fileName)

#processRealDeal

def processFile(): #THIS IS THE MAIN FUNC

   ''' print(fileName) get input name and output variables
    print(outPath)'''


print (OpenFile)

label = ttk.Label(root, text ="",foreground="black",font=("Helvetica", 16))
label.pack()


#Button Open-----------

button1 = Button (text = "Open File", command = OpenFile)
button1.pack()


#Button Start---------
buttonStart = Button (text = "Start Process", command = lambda: printFilename("Hello World!!!"))#give as parameter inputFile and link
buttonStart.place(height=50, width=100)

#Button Open-----------

button3 = Button (text = "Output Folder", command = outputFolder)
button3.pack()


#Menu Bar ----------------

menu = Menu(root)
root.config(menu=menu)

file = Menu(menu)


file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())

menu.add_cascade(label = 'File', menu = file)


window(root)
root.mainloop()

И тестовая функция печатает выбранный файл. Таким образом, глобальная переменная теперь содержит правильное значение.

Так что просто объявите это сверху, и вы сможете получить значение

0 голосов
/ 24 января 2019

Если вы используете функцию в переменной, возвращаемый результат функции сохраняется в переменной.

def Function1(x):
    return x*2

var1 = Function1(5)

Тогда var1 = 10.

Но что касается ваших кнопок?хотите получить ввод от пользователя, который будет сохранен при нажатии кнопки, или вы хотите, чтобы кнопка отправила установленное значение?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...