2012-10-14 4 views
0

안녕하세요 전체,내 항목 위젯에 텍스트가 표시되지 않는 이유

os.walks에서 일부 데이터를 수집하는 작은 앱이 있습니다. 그것이 작동하는 동안 나는 "Processing"텍스트가있는 엔트리 위젯을 넣고 걷는 것이 완료되었을 때 "Completed"로 변경하는 것이 좋을 것이라고 생각했다.

문제는 "처리 중"이 나타나지 않습니다. 처리 시간이 너무 오래 걸리기 때문에 처리가 너무 빨리 끝나지 않습니다.

def do_search(): 

txtProgress.delete(0,END) 
txtProgress.insert(0, "Processing Data") 

print 'do_search called' 

arrayOfDirectories = [] # Store the categories here 
global path 
print 'The value for path = ' + path # Delete this in final 
searchpath = path 
print 'The value for searchpath = ' + searchpath # Delete this in final 

for (searchpath, directories, files) in os.walk(searchpath): 
    for directory in directories: 
     arrayOfDirectories.append(directory) # Create an array or dirs to use for the categories 

id = 1 
finalJSON = '[' 

for eachDirectory in arrayOfDirectories: 
    readpath = os.path.join(path, eachDirectory, 'URLS') # Grab each list of URLs 
    print('readpath = ' + readpath) 

    if os.path.exists(readpath): 
     file = open(readpath) # Open the list of URLs 
     for lines in file: # Step through each URL in turn 

      ruleString = '{"id":' + str(id) + ',"enabled":true, "category":"' + eachDirectory + '","description":"' + lines + '","flagged":true,"string":"' + lines + '","name":"","javaClass":"com.untangle.uvm.node.GenericRule","blocked":true}' 
      #print(ruleString) 
      finalJSON = finalJSON + ruleString # Create a rule and add it to the final string 
      id = id + 1 # Increment the id after each rule 
     file.close() # Close the file when all have been read 

작동하지 않으면 열차가 부숴 지지만 텍스트가 표시되지 않는 이유를 이해하지 못합니다.

항상 그렇듯이 모든 조언이 감사하게 받아 들여졌습니다.

+0

들여 쓰기를 수정하고 수동 json 대신'import json'을 사용하십시오. 또한 전역 변수를 건드려서는 안되며, 파이썬으로 몇 년 동안 코딩하지 않았습니다. – dav1d

+0

들여 쓰기에 어떤 문제가 있는지 잘 모르겠습니다. json 모듈이 있다는 것을 몰랐습니다. 나는 일을 끝내기 위해 무엇이든 살아 있도록 코드를 작성하지 않습니다. –

답변

1

요약하면 프로그램에 표시 할 기회가 없습니다. 화면 다시 그리기는 다시 칠하기 이벤트의 결과로만 발생하므로 이벤트 루프가 해당 이벤트를 처리 할 기회가 없으면 아무 것도 표시되지 않습니다. 이것은 Tkinter에만 국한된 것이 아닙니다. 모든 GUI 툴킷은 이런 방식으로 작동합니다.

간단한 해결책은 화면을 업데이트 할 때마다 txtProgress.update_idletasks()으로 전화하는 것입니다. 이렇게하면 화면을 새로 고치는 이벤트를 실행할 수 있습니다. 이것은 최선의 해결책은 아니지만 귀하의 즉각적인 문제를 해결할 수 있습니다.

가장 좋은 해결책은 프로그램을 리팩터링하여 별도의 스레드 또는 프로세스에서 장기 실행 작업을 수행하거나 이벤트 루프를 반복 할 때마다 한 번에 하나씩 수행 할 수있는 청크로 작업을 중단시키는 것입니다.

+0

고마워요. 항상 배울 무언가. 나는 스레딩을 스스로 가르 칠 필요가 없거나, 욕망을 갖지 않기 때문에 진행형 기능을 조용하게 죽게 만들 수 있다고 생각합니다. 그래도 뭔가 배울 수있는 간단한 솔루션을 사용해 보겠습니다. 다시 한번 감사드립니다. –

0

이 프로젝트에 최종 수정 만하십시오. Bryan의 제안을 모두 적용하고 .update_idletasks() 메서드를 사용하고 스레딩을 사용했습니다. 마지막 코드는 원하는 작동하고 다음과 같습니다 도움말들에 대한

from Tkinter import * 
import os 
import threading 
from tkFileDialog import askdirectory 

##################################### 
# Put the grunt stuff up here  # 
##################################### 
def loadpath(): 

    print 'loadpath called' 
    global path 
    path = askdirectory() 
    txtPath.delete(0, END) 
    txtPath.insert(0, path) 

def update_the_status(): 
    txtProgress.delete(0,END) 
    txtProgress.insert(0, "Processing Data") 
    txtProgress.update_idletasks() 

def do_the_search(): 
    print 'do_search called' 

    arrayOfDirectories = [] # Store the categories here 
    global path 
    print 'The value for path = ' + path # Delete this in final 
    searchpath = path 
    print 'The value for searchpath = ' + searchpath # Delete this in final 

    for (searchpath, directories, files) in os.walk(searchpath): 
     for directory in directories: 
      arrayOfDirectories.append(directory) # Create an array or dirs to use for the categories 

    id = 1 
    finalJSON = '[' 
    for eachDirectory in arrayOfDirectories: 
     readpath = os.path.join(path, eachDirectory, 'URLS') # Grab each list of URLs 
     print('readpath = ' + readpath) 

    if os.path.exists(readpath): 
     file = open(readpath) # Open the list of URLs 
     for lines in file: # Step through each URL in turn 

      ruleString = '{"id":' + str(id) + ',"enabled":true, "category":"' + eachDirectory + '","description":"' + lines + '","flagged":true,"string":"' + lines + '","name":"","javaClass":"com.untangle.uvm.node.GenericRule","blocked":true}' 
      #print(ruleString) 
      finalJSON = finalJSON + ruleString # Create a rule and add it to the final string 
      id = id + 1 # Increment the id after each rule 
     file.close() # Close the file when all have been read 

finalJSON = finalJSON + ']' # Close the JSON array 

outputPath = os.path.join(os.path.dirname(path), 'Blacklist.json') 
print('Output path = ' + outputPath) 

outputFile = open(outputPath, 'w') 
outputFile.write(finalJSON) 
txtProgress.delete(0,END) 
txtProgress.insert(0,"Process Complete") 
outputFile.close() 


def do_search(): 

    WriteThread = threading.Thread(target=update_the_status()) 
    CalcThread = threading.Thread(target=do_the_search()) 
    WriteThread.start() 
    CalcThread.start() 

def do_quit(): 
    print 'do_quit called' 
    sys.exit() 

##################################### 
#  Build the interface   # 
##################################### 

# Some global variables 
path = '' 

# Create the application window and give it a title. 
main = Tk() 
main.geometry('600x400') 
main.title('Blacklist JSON array builder') 

# Populate the window with widgets. 
lbSpace1 = Label(main, text='') 
lbSpace1.grid(row=0, column=0, columnspan=3) 

lbDesc = Message(main, width=800, text='After you have unzipped the .tar file select the blacklist folder \nthat has been created using the browse button. Then click start. The Blacklist.json \nfile will be created in the same directory as the Blacklist folder.') 
lbDesc.grid(row=1, column=0, columnspan=4, pady=10) 

lbPath = Label(main, text='Directory') 
lbPath.grid(row=2, column=0, pady=10) 

txtPath = Entry(main, width=50) 
txtPath.grid(row=2, column=1) 

pbPath = Button(main, text='Browse', command=loadpath) 
pbPath.grid(row=2, column=2) 

lbSpace2 = Label(main, text='') 
lbSpace2.grid(row=3, column=0, columnspan=3) 

pbStart = Button(main, text='Begin', command=do_search) 
pbStart.grid(row=4, column=1, sticky=W, pady=20) 

pbQuit = Button(main, text='Quit', command=do_quit) 
pbQuit.grid(row=4, column=2, sticky=W) 

lbSpace3 = Label(main, text='') 
lbSpace3.grid(row=5, column=0, columnspan=3) 

txtProgress = Entry(main, width=50) 
txtProgress.grid(row=6, column=1) 
txtProgress.insert(0,'Waiting') 


mainloop() 

감사합니다.

관련 문제