John White
John White

Reputation: 161

This tiny Tkinter program works in Python 2 and 3, but why the odd behaviour in Python 3?

New to Tkinter, I 'wrote' the code below to draw a page of squared paper with bold lines at 10-square intervals.

It runs OK in Python 2 (with the change from 'tkinter' to 'Tkinter'). In Python 3 it runs, but the emboldening is only applied to vertical lines.

Not the most urgent problem in the world, I'm hoping it might raise a bit of interest matching my own curiosity...

'''
    SquaredPaper app, based on Canvas example from 
    http://effbot.org/tkinterbook/tkinter-index.htm
'''
# CONSTANTS
A4Hmm = 297
A4Wmm = 210
PXperMM = 3
A4_HEIGHT = A4Hmm * PXperMM
A4_WIDTH  = A4Wmm * PXperMM
SQUARE_SIDE = 5*PXperMM
NSQUARES_H = A4_HEIGHT/SQUARE_SIDE
NSQUARES_W = A4_WIDTH/SQUARE_SIDE 

from tkinter import *

master = Tk()

w = Canvas(master, width=A4_WIDTH, height=A4_HEIGHT)
w.pack()
paper = w.create_rectangle(0, 0, A4_WIDTH, A4_HEIGHT)

count = NSQUARES_H
pos = 0
while count > 0:
    lw = 1 if count%10 else 2
    w.create_line(0, pos, A4_WIDTH, pos, width=lw)
    pos += SQUARE_SIDE

    count -= 1

count = NSQUARES_W
pos = 0
while count > 0:
    lw = 1 if count%10 else 2
    w.create_line(pos, 0, pos, A4_HEIGHT, width=lw)
    pos += SQUARE_SIDE

    count -= 1



mainloop()

Upvotes: 0

Views: 45

Answers (1)

FrainBr33z3
FrainBr33z3

Reputation: 1105

The problem arises due the way division is handled in each version.

In Python 2.7, the division operator / outputs an integer value, if the 2 inputs are integers.

Whereas, in Python 3, a float value is returned for the same.

This makes the code usable in Python 2.7 and not in 3, as the variable NSQUARES_H is returned as a float and hence the else condition in lw = 1 if count%10 else 2 is never executed.

If you want to run the same in Python 3, round the value of NSQUARES_H or convert it into an int

Upvotes: 2

Related Questions