jay020420
jay020420

Reputation: 1

About tkinter directory path

I want to insert the path of the file in #here! but my terminal spends name 'dirname' is not defined message :(...

I don't know why that error occurs.. I elide some codes :)... Thank you for reading

import tkinter
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
from PIL import Image
import pytesseract

def ask():
    dirname = filedialog.askopenfile(
        initialdir='C:/Users/PC/Desktop',
        title='파일 선택',
        filetypes=(('png 파일','*.png'), ('jpg 파일', '*jpg'), ('모든 파일 보기', '*.*'))
    )
    filename = tkinter.filedialog.asksaveasfilename()
    Txt.configure(text='경로 :' + dirname.name)

def ocr():
    pytesseract.pytesseract.tesseract_cmd = r'C:\Users\PC\AppData\Local\Tesseract-OCR\tesseract.exe'
    text = pytesseract.image_to_string(Image.open(#here!), lang="kor")
    print(text)

Txt = Label(window, text = ' ')
Txt.pack()

path_button = Button(window, text="경로 선택하기", command = ask)
path_button.pack()

button = Button (window, width = 10, text = "선택하기", overrelief="solid", command = ocr) # 확인 버튼
button.pack()

window.mainloop()

Upvotes: 0

Views: 49

Answers (1)

Eric Roy
Eric Roy

Reputation: 343

In ask() you are setting to variables: dirname and filename.

These two variables are set as local variables by default (they will not be visible outside the ask() function). That's why you can't access them.

You can patch this by setting them to global:

#AFTER THE IMPORTS
filename = "some_default_filename.png"
dirname = "/some/default/path/"

#INSERT THIS AT THE BEGINNING OF ASK()
def ask():
    global filename
    global dirname

    filename = ..... #Your code

#YOU WILL BE ABLE TO ACCESS THEM TO OCR()
def ocr():
    #.......
    Image.open(dirname + filename)
    #.......

Note that if you don't need to edit the variable, you don't need to declare it global, python will assume that by default. You can still add global dirname and global filename if you wish, the code will run as well.

Upvotes: 1

Related Questions