2010-12-12 5 views
1

저는 파이썬에서 GUI로 일부 작업을하고 있습니다. Tkinter 라이브러리를 사용하고 있습니다. 지금은 조립하는 방법을 모르는tkinter 이벤트에 어떻게 응답합니까?

from Tkinter import *    
import tkFileDialog,Tkconstants,collections 

root = Tk() 
root.title("TEST") 
root.geometry("800x600") 

button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5} 
fileName = '' 
def openFile(): 
    fileName = tkFileDialog.askopenfile(parent=root,title="Open .txt file", filetypes=[("txt file",".txt"),("All files",".*")]) 
Button(root, text = 'Open .txt file', fg = 'black', command= openFile).pack(**button_opt) 



frequencies = collections.defaultdict(int) # <----------------------- 
with open("test.txt") as f_in:     
    for line in f_in: 
     for char in line: 
      frequencies[char] += 1 
total = float(sum(frequencies.values()))  #<------------------------- 



root.mainloop() 

: 나는 시작

frequencies = collections.defaultdict(int) # <----------------------- 
with open("test.txt") as f_in:     
    for line in f_in: 
     for char in line: 
      frequencies[char] += 1 
total = float(sum(frequencies.values()))  #<------------------------- 

:

나는이 .txt 파일을 열고 처리의이 비트를 할 것입니다 버튼을, 필요 내 코드 그래서 버튼을 누르면 실행됩니다.

답변

2

주된 문제점은 tkFileDialog.askopenfile()입니다. 파일 이름이 아닌 file이 반환됩니다. 이 다음은 다소간 나를 위해 일하는 것 같았다 :

from Tkinter import * 
import tkFileDialog, Tkconstants,collections 

root = Tk() 
root.title("TEST") 
root.geometry("800x600") 

def openFile(): 
    f_in = tkFileDialog.askopenfile(
          parent=root, 
          title="Open .txt file", 
          filetypes=[("txt file",".txt"),("All files",".*")]) 

    frequencies = collections.defaultdict(int) 
    for line in f_in: 
     for char in line: 
      frequencies[char] += 1 
    f_in.close() 
    total = float(sum(frequencies.values())) 
    print 'total:', total 

button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5} 
fileName = '' 
Button(root, text = 'Open .txt file', 
     fg = 'black', 
     command= openFile).pack(**button_opt) 

root.mainloop() 

빠르고 간단한 GUI 프로그램을 만들기 위해 내가보기 엔 Tk 간단하면서도 매우 강력한이 같은 일을 파이썬 모듈을 --based, EasyGUI하는 것이 좋습니다.

+0

많은 도움;) 도움을 청합니다 – thaking

+0

3 분 후에 외쳐야합니다. +1 좋은 답변, 훨씬 덜 복잡합니다. – John

0

openFile() 함수에서 사용자에게 파일 이름을 물어 본 직후에 코드를 입력하십시오!

+0

글쎄,이 시도는 아니지만, 내가 그것을 실행할 때 먼저 text.file을 열려면 창 대화 상자를여십시오. 단추를 누른 다음 그것을 클릭하고 .txt 파일을 열고 "코드"에있는 내용을 수행하십시오 – thaking

1

시도 뭔가 이렇게 조금 배치 : 또한 읽을 수 있습니다

class my_app(): 
    def __init__(): 
     self.hi_there = Tkinter.Button(frame, text="Hello", command=self.say_hi) 
     self.hi_there.pack(side=Tkinter.LEFT) 

    def say_hi(): 
     # do stuff 

: 영업 이익은 예를 원하는 : 편집 And this one.

This tutorial on Tkinter,

그의 코드 (나는 생각한다)와 함께 그것이 여기에있다 :

from Tkinter import *    
import tkFileDialog,Tkconstants,collections 

class my_app: 
    def __init__(self, master): 
     frame = Tkinter.Frame(master) 
     frame.pack() 

     self.button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5} 
     self.button = Button(frame, text = 'Open .txt file', fg = 'black', command= self.openFile).pack(**button_opt) 

     self.calc_button = Button(frame, text = 'Calculate', fg = 'black', command= self.calculate).pack() 

     self.fileName = '' 

    def openFile(): 
     fileName = tkFileDialog.askopenfile(parent=root,title="Open .txt file", filetypes=[("txt file",".txt"),("All files",".*")]) 

    def calculate(): 
     ############################################### *See note 
     frequencies = collections.defaultdict(int) # <----------------------- 
     with open("test.txt") as f_in:     
      for line in f_in: 
       for char in line: 
        frequencies[char] += 1 
     total = float(sum(frequencies.values()))  #<------------------------- 
     ################################################ 

root = Tk() 

app = App(root) 

root.title("TEST") 
root.geometry("800x600") 

root.mainloop() 

* 참고 : 코드가 어디에서 왔는지 알 수 없으므로 그 블록을 어떻게 처리해야하는지 잘 모릅니다. 이 예제에서는 실행하도록 설정했습니다

+0

도움을 주셔서 감사합니다.하지만 여전히 작동하지 않습니다. 당신의 예제 코드를 복사 해 주시겠습니까? – thaking

관련 문제