HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python tkinter GUI

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
guitkinterpython

Problem

I'm making a little Python script that reads a text file and puts it on a HTML page. I haven't finished that part yet, but I've been working on the GUI with tkinter. Is my code sloppy?

```
from Tkinter import *
import time
from datetime import datetime
#init variables
global r
r = 0
global delay
delay = 1000
#for testing
global lat
lat = "41.5345"
global lon
lon = "-85.343"
global zoom
zoom = 0
global mapDir
mapDir = ""
global mapDirEnabl
mapDirEnabl = 0
#clear log file
log = open("xpyMapLog.txt", "w")
log.write("")
log.close()
global log
log = open("xpyMapLog.txt", "a")
logStartMessage = "RUN TIME EXECUTED AT: %s \n" % str(datetime.now())
log.write(logStartMessage)

#error check
class safe:
def __init__(self, function):
self.function = function

def __call__(self, *args):
try:
return self.function(*args)
except Exception, e:
errorMsg = "Error: %r" % str(e)
log.write(errorMsg)
print "Error: %s" % e
#
#
#

#open data file
@safe
def openData():
global Data
Data = open("Data.txt", "r")
#
openData()

#init root window
root = Tk()
root.geometry("550x300+200+200")
root.title("XPYmap for x-plane 10")

#init functions

@safe
def mainLoop():
if r == 1:
#****
#DATA READING AND WRITING TO MAP FILE!*
#****
print "Hello"
#im not done with the data reading yet so just pretend its here

#######################################
#
#

@safe
def start():
global r
r = 1
mainLoop()
#
@safe
def stop():
global r
r = 0
posLabl["text"] = "Position: NOT RUNNING"
#
@safe
def setZoom(z):
global zoomlabel
zoom = int(z)
curntZoomLabl["text"] = "Current zoom level: %s" % zoom
#
@safe
def setDelay(d):
print "delay"
global delay
delay = int(d)
delayInSec = delay / 1000 # get seconds from milisec

Solution

Is my code sloppy?

It is, but there are very specifics things you can do to address that. Good news! First, use http://pep8online.com/ to make sure that your code follows PEP 8, which is a standard that most Python coders follow to make sure that every Python code can be easily understood by every Python coder.

from Tkinter import *
import time
from datetime import datetime


You need two spaces after the module imports.

#init variables
global r
r = 0
global delay
delay = 1000
#for testing
global lat
lat = "41.5345"
global lon
lon = "-85.343"
global zoom
zoom = 0
global mapDir
mapDir = ""
global mapDirEnabl
mapDirEnabl = 0


Please don't use global variables, you don't need them and they only clutter your code. The good thing about a function is that I can understand it by only looking at it. With global variables, it's not true anymore and I need to be aware of all those variables.

#clear log file
log = open("xpyMapLog.txt", "w")
log.write("")
log.close()
global log
log = open("xpyMapLog.txt", "a")
logStartMessage = "RUN TIME EXECUTED AT: %s \n" % str(datetime.now())
log.write(logStartMessage)


Python has a powerful logging module that you could use. To clear the log file, simply open it in 'w' mode.

#error check
class safe:
    def __init__(self, function):
        self.function = function

    def __call__(self, *args):
        try:
            return self.function(*args)
        except Exception, e:
            errorMsg = "Error: %r" % str(e)
            log.write(errorMsg)  
            print "Error: %s" % e


Make sure that you know why and when you're using the safe decorator. It's a bad idea most of the time: most exceptions are not recoverable and you should instead 1/ make sure they do not happen 2/ or recover when you know how to recover.

#
    #
#


Remove those, and either get used to Python's indentation or find an editor that helps you to visualize the scope of your blocks.

#open data file
@safe
def openData():
    global Data
    Data = open("Data.txt", "r")
#
openData()


Why is this a function? You only need Data = open("Data.txt", "r") and nothing else if it's not a function. And you won't need the nasty global. @safe also makes no sense here. What do you want to do when opening the data file fails?

#init root window
root = Tk()
root.geometry("550x300+200+200")
root.title("XPYmap for x-plane 10")


Note that Tkinter is not considered a very nice Python library anymore, but I don't know what is the recommended one nowadays. Please rewrite your code considering what I have said already, and maybe resubmit the result on Code Review when it's done.

Code Snippets

from Tkinter import *
import time
from datetime import datetime
#init variables
global r
r = 0
global delay
delay = 1000
#for testing
global lat
lat = "41.5345"
global lon
lon = "-85.343"
global zoom
zoom = 0
global mapDir
mapDir = ""
global mapDirEnabl
mapDirEnabl = 0
#clear log file
log = open("xpyMapLog.txt", "w")
log.write("")
log.close()
global log
log = open("xpyMapLog.txt", "a")
logStartMessage = "RUN TIME EXECUTED AT: %s \n" % str(datetime.now())
log.write(logStartMessage)
#error check
class safe:
    def __init__(self, function):
        self.function = function

    def __call__(self, *args):
        try:
            return self.function(*args)
        except Exception, e:
            errorMsg = "Error: %r" % str(e)
            log.write(errorMsg)  
            print "Error: %s" % e
#open data file
@safe
def openData():
    global Data
    Data = open("Data.txt", "r")
#
openData()

Context

StackExchange Code Review Q#37154, answer score: 4

Revisions (0)

No revisions yet.