Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python에서 파일 선택 대화상자 띄워 사용자가 파일을 읽도록 하는 방법 (Tkinter filedialog)


Python 애플리케이션에서 대화상자(dialog box)가 어떻게 동작하는지 궁금해 본 적이 있다면, 아마 filedialog 모듈에 대해 들어보았을 것입니다. 이 모듈은 Tkinter에 기본으로 포함되어 있으며, 시스템의 파일을 다루기 위한 다양한 종류의 대화상자를 화면에 표시할 수 있는 내장 함수들을 제공합니다.

가장 일반적인 활용 사례는 filedialog.askopenfilename() 함수를 사용해 사용자가 시스템에서 파일을 탐색하고 열도록 유도하는 것입니다. 이후 스크립트는 사용자가 선택한 파일 형식에 따라 읽기(read) 또는 쓰기(write) 작업을 수행하도록 프로그래밍됩니다.

파일 경로를 확보한 후에는 open(file, 'mode') 함수를 사용해 원하는 모드로 파일을 열고 각종 작업을 처리할 수 있습니다. 이번 글에서는 사용자에게 텍스트 파일을 열도록 요청하는 간단한 애플리케이션을 만들어 보겠습니다. 파일이 선택되어 열리면 'read' 모드를 사용해 파일 내용을 읽어오는 방식으로 동작합니다.

예제 코드

# Import the library
from tkinter import *
from tkinter import filedialog

# Create an instance of window
win=Tk()

# Set the geometry of the window
win.geometry("700x300")

# Create a label
Label(win, text="Click the button to open a dialog", font='Arial 16 bold').pack(pady=15)

# Function to open a file in the system
def open_file():
    filepath = filedialog.askopenfilename(title="Open a Text File", filetypes=(("text     files","*.txt"), ("all files","*.*")))
    file = open(filepath,'r')
    print(file.read())
    file.close()

# Create a button to trigger the dialog
button = Button(win, text="Open", command=open_file)
button.pack()

win.mainloop()

실행 결과

위 코드를 실행하면 대화상자를 여는 버튼이 포함된 창이 화면에 나타납니다.

Python에서 파일 선택 대화상자 띄워 사용자가 파일을 읽도록 하는 방법 (Tkinter filedialog)

버튼을 클릭한 뒤 텍스트 파일을 선택하여 열면, 해당 파일의 전체 내용이 콘솔에 출력됩니다.

Centralized Database Vs Blockchain

A blockchain can be both permissionless (like Bitcoin or Ethereum) or permissioned (like the different Hyperledger blockchain frameworks). A permissionless blockchain is also known as a public blockchain, because anyone can join the network. A permissioned blockchain, or private blockchain, requires pre-verification of the participating parties within the network, and these parties are usually known to each other.

Types of Blockchains
The choice between permissionless versus permissioned blockchains should be driven by the particular application at hand (or use case). Most enterprise use cases involve extensive vetting before parties agree to do business with each other. An example where a number of businesses exchange information is supply chain management. The supply chain management is an ideal use case for permissioned blockchains.

You would only want trusted parties participating in the network. Each participant that is involved in the supply chain would require permissions to execute transactions on the blockchain. These transactions would allow other companies to understand where in the supply chain a particular item is.