Hmm, irgendwie funktioniert das nur halb..

Fragen zu Tkinter.
Antworten
powerslide
User
Beiträge: 51
Registriert: Freitag 10. Dezember 2004, 09:05
Wohnort: Erlangen
Kontaktdaten:

Hallo,

nachdem ich die anderen Probleme losgeworden bin...

habe ich nurn 5 andere :roll:

also zur grundsätzlichen funktionalität..

ich will entweder eine einzelne datei oder alle dateien eines ordners convertieren..

je nachdem was oben angewählt ist steht die suche nach dateien oder die nach ordnern zur verfügung..

mit cancel soll einfach das fenster auf init-zustand zurück gestezt werden..

mit click auf ok soll gecheckt werden welcher converter gestartet werden soll.. danach soll der jeweilige converter gestartet werden.. bei single file wird noch gleich geprüft ob die datei überhaupt eine xml datei ist..

dann wird convertiert.. dann soll gefragt werden ob das backup geöscht werden soll.. danach soll gefragt werden ob man weiter convertieren will oder nicht.. danach entweder cancel ausführen.. bzw eben beenden..

eigentlich sollte das alles funktionieren aber irgendwie klappt das nicht so ganz..

überprüfung auf xml funzt nicht.
löschen der backups geht nicht..
cancel wird nicht ausgeführt
frame.quit auch nicht so richtig

ich hoffe ihr könnt mir helfen

hier mein aktueller code

Code: Alles auswählen

#---------------------------------------------------------
# imports

import os
import string
import re
from Tkinter import *
from tkFileDialog import *
from ScrolledText import *
from tkMessageBox import *

#---------------------------------------------------------
# get directory

def get_dir():
    path.insert(0,askdirectory())

#---------------------------------------------------------
# get filepath

def get_file():
    datei.insert(0,askopenfilename())

#---------------------------------------------------------
# cancel

def can():
    old1 = path["state"]
    old2 = datei["state"]
    path["state"] = "normal"
    datei["state"] = "normal"                 
    path.delete(0,END)
    datei.delete(0,END)
    path["state"] = old1
    datei["state"] = old2
    v.set('1')
    path["state"] = "disabled"
    direct["state"] = "disabled"
    datei["state"] = "normal"
    dat["state"] = "normal"
    set_out('Please select a file for conversion.', 'y')

#---------------------------------------------------------
# convert a single file window behaviour
    
def sing():
    path["state"] = "disabled"
    direct["state"] = "disabled"
    datei["state"] = "normal"
    dat["state"] = "normal"
    set_out('Please select a file for conversion.', 'y')

#---------------------------------------------------------
# convert multiple files window behaviour
   
def mult():
    path["state"] = "normal"
    direct["state"] = "normal"
    datei["state"] = "disabled"
    dat["state"] = "disabled"
    set_out('Please select a directory to make the rogram search for files.\nNote: ALL xml files will be converted!', 'y')

#---------------------------------------------------------
# print messages to messagescreen

def set_out(text, opt):
    text = text + '\n--------------------------------------------------------------------------------------------------------------------------\n'
    ausgabe["state"] = "normal"
    if (opt == 'y'):
        ausgabe.delete(1.0,END)
    ausgabe.insert(END, str(text))
    ausgabe["state"] = "disabled"
    ausgabe.see(END)

#---------------------------------------------------------
# start conversion

def start():
    x = v.get()
    if (x == 1):
        pfad = datei.get()
        set_out(pfad, 'n')
        if (pfad == ''):
            showerror('Error','You must specify a file to convert!')
            return
        convertfile(pfad)
        pfad, filename = os.path.split(pfad)
        bak_killer_call(pfad)
        restart()
    elif (x == 2):
        pfad = path.get()
        set_out(pfad, 'n')
        if (pfad == ''):
            showerror('Error','You must specify a directory!')
            return
        multipleFiles(pfad, '.xml')
        bak_killer_call(pfad)
        restart()

#---------------------------------------------------------
# restart program or quit

def restart():
    eingabe = askyesno('More...','Would you like to convert more files?')
    if (eingabe == 'True'):
        #can()
        return
    elif (eingabe == 'False'):
        set_out('phasing down application','n')
        frame.quit()

#---------------------------------------------------------    
# filter definitions
    
def f1(text):
    return text.replace("[","").replace("]","")

def f2(text, old, new):
    while 1:
        ort = re.search (old, text)
        if ort == None:
            break
        text = re.sub (old, new, text)
    return text

def f3(text):
    while 1:
        ort = re.search ('(.+?)', text)
        if ort == None:
            break
        text = re.sub('(.+?)', r'\1', text)
    return text     

#---------------------------------------------------------
# multiple file search and convert
  
def multipleFiles(path, extension, depth=0):
    for item in os.listdir(path):
        itemWithPath = os.path.join(path, item)
        if item.endswith(extension):
            datei = itemWithPath
            set_out('Starting conversion', 'n')
            in_file = open(datei,"r")
            inhalt = in_file.read()
            in_file.close()
            bak = datei + '_bak'
            try:
                bak_file = open(bak, 'w')
                bak_file.write(inhalt)
                bak_file.close()
            except IOError:
                set_out('Backup file could not be generated','n')
            new_string = str(inhalt)
            new_string = string.replace(new_string, '[Q-]', '')
            new_string = string.replace(new_string, '[PM-]', '')
            new_string = string.replace(new_string, '[role]', '')
            #new_string = f1(new_string)
            new_string = f3(new_string)
            new_string = f2(new_string, '', '')
            new_string = f2(new_string, '', '')
            try:
                out_file = open(datei, "w")    
            except IOError:
                set_out('File could not be opened!','n')
            out_file.write(new_string)
            out_file.close()
            set_out('File converted and written','n')
        if os.path.isdir(itemWithPath):
            multipleFiles(itemWithPath, extension, depth + 1)

#---------------------------------------------------------
# single file convert

def convertfile(datei):
    set_out('Starting conversion','n')
    ext_match = datei.endswith('.xml')
    if (ext_match == 'False'):
        showerror('Error','Invalid File!')
        return
    in_file = open(datei,"r")
    inhalt = in_file.read()
    in_file.close()
    bak = datei + '_bak'
    try:
        bak_file = open(bak, 'w')
        bak_file.write(inhalt)
        bak_file.close()
    except IOError:
        set_out('Backup file could not be generated','n')
    new_string = str(inhalt)
    new_string = string.replace(new_string, '[Q-]', '')
    new_string = string.replace(new_string, '[PM-]', '')
    new_string = string.replace(new_string, '[role]', '')
    new_string = f1(new_string)
    new_string = f3(new_string)
    new_string = f2(new_string, '', '')
    new_string = f2(new_string, '', '')
    try:
        out_file = open(datei, "w")    
    except IOError:
        set_out('File could not be opened!','n')
    out_file.write(new_string)
    out_file.close()
    set_out('File converted and written','n')

#---------------------------------------------------------
# bak_killer call

def bak_killer_call(pfad):
    set_out('starting remove engine','n')
    eingabe = askyesno('Remove backup?','Would you like to remove the backup [*.xml_bak] files?')
    if (eingabe == 'False'):
        set_out('To remove backup files, simply run bak_remover.','n')
        return
    elif (eingabe == 'True'):
        bak_killer(pfad, '.xml_bak')

#---------------------------------------------------------
# backup killer                

def bak_killer(path, extension, depth=0):
    for item in os.listdir(path):
        itemWithPath = os.path.join(path, item)
        if item.endswith(extension):
            os.remove (itemWithPath)
        if os.path.isdir(itemWithPath):
            bak_killer(itemWithPath, extension, depth + 1)

#---------------------------------------------------------
# build gui

root=Tk()

frame=Frame(root)
frame.pack(expand=YES)

root.title('XML converter vol 1.0')

selectrahmen = Frame(root, relief="groove", borderwidth="2")
selectrahmen.pack(fill="x")

select1 = Frame(selectrahmen)
select1.pack(fill="x")
select2 = Frame(selectrahmen)
select2.pack(fill="x")

selectLab = Label(select1, text='Would you like to convert a single file or multiple files?')
selectLab.pack(side = "top", anchor="w")

v = IntVar()
Radiobutton(select2, text="single", variable=v, value=1, command=lambda: sing()).pack(side="left")
Radiobutton(select2, text="multiple", variable=v, value=2, command=lambda: mult()).pack(side="left")
v.set('1')
        
eingaberahmen = Frame(root, relief="groove", borderwidth="2")
eingaberahmen.pack(fill="x")

suchDatei = Label(eingaberahmen, text = 'File: ')
suchDatei.grid(row=1,column=1)

datei = Entry(eingaberahmen, width=45)
datei.grid(row=1,column=2)

dat = Button(eingaberahmen, text = 'search', command=lambda: get_file())
dat.grid(row=1,column=3)

suchPfad = Label(eingaberahmen, text = 'Directory: ')
suchPfad.grid(row=2,column=1)

path = Entry(eingaberahmen, width=45, state='disabled')
path.grid(row=2,column=2)

direct = Button(eingaberahmen, text = 'search',state='disabled', command=lambda: get_dir())
direct.grid(row=2,column=3)

eingaberahmen2 = Frame(root)
eingaberahmen2.pack()

cancel = Button(eingaberahmen2, text = 'Cancel', command=lambda: can())
cancel.pack(side='left')
ok = Button(eingaberahmen2, text = 'OK', command=lambda: start())
ok.pack(side='left')

ausgaberahmen = Frame(root, relief="groove", borderwidth="2")
ausgaberahmen.pack(fill="x")

ausgabeLab = Label(ausgaberahmen, text = 'Messagescreen').pack(side = "top", anchor="w")

ausgabe = ScrolledText(ausgaberahmen, width=61, height=10, state='disabled', bg='white')
ausgabe.pack()
set_out('Please select a file for conversion.', 'y')

root.mainloop()

slide
How many people can read hex if only you and dead people can read hex?

There are 10 types of people in the world: Those who understand binary, and those who don't...
Dookie
Python-Forum Veteran
Beiträge: 2010
Registriert: Freitag 11. Oktober 2002, 18:00
Wohnort: Salzburg
Kontaktdaten:

Hi slide,

uiuiui, lauter globale Variablen, ich würd erstmal etwas Struktur in das Script bringen, dann lösen sich sicher 3 von 5 Problemen von selber. ;)
Dann auch noch die from foo import *, zusammen mit den globalen Variablen da sind Probs schon vorprogrammiert.

Sorry, daß ich dir da nicht besser helfen kann/will.


Gruß

Dookie
[code]#!/usr/bin/env python
import this[/code]
DER Olf
User
Beiträge: 283
Registriert: Mittwoch 24. Dezember 2003, 19:32

hi powerslide,

was genau funktioniert nicht?

gibt es fehler?
oder funktioniert es einfach nicht?

und warum steht bei (fast?) jedem command deiner widgets ein lambda?

probiers mal so:

Code: Alles auswählen

dat = Button(eingaberahmen, text = 'search', command=get_file) 
wenn das immer noch nicht hilft, änder mal den funktionsinhalt
in

print "eine debug message"

damit kannst du auhc überprüfen, ob alles funktioniert.

mfg Olf

### edit ###
ich hab versucht deinen code zu ändern, aber da konnte ich so schnell nicht durchblicken
schreib am besten alles in eine klasse :>

mfg Olf
Antworten