Maybe I was not clear enough.

If you give a variable to a control object in tkinter, then the control reads its state from this variable. If you do not keep track of this variable, then you loose the state of the control.

Unfortunately (?) the the control's binding to the variable seems to be weak. So if you loose reference to the control's variable in your code, then the control is loosing it too. So something undefined happens....

So instead of
Line 46:
v = IntVar()

Do this:
and update all occurences.

Line 46:
v = IntVar()

v goes out of scope.

If you bind v to something persistent (self), then it works.

How did you plan to read that variable anyway?

Please post a working code, to help others. Try to copy-paste your own posted code into a .py file and see, that it does not work. There is a syntax error, not just intendation problems. The mainloop call is missing, too.

I have corrected the code, and hopefully solved your problem:

import tkinter

class MPG: 
    def __init__(self):
    #create window
        self.main_window = tkinter.Tk()

        #create 4 frames
        self.gallons_frame = tkinter.Frame(self.main_window)
        self.miles_frame = tkinter.Frame(self.main_window)
        self.mpg_frame = tkinter.Frame(self.main_window)
        self.button_frame = tkinter.Frame(self.main_window)
        self.error_frame = tkinter.Frame(self.main_window)

        self.gallons_label = tkinter.Label(self.gallons_frame, \
                                        text= "Enter the number of gallons:")
        self.gallons_entry = tkinter.Entry(self.gallons_frame, \
        self.miles_label = tkinter.Label(self.miles_frame, \
                                        text= "Enter the number of miles:")
        self.miles_entry = tkinter.Entry(self.miles_frame, \
        self.result_label = tkinter.Label(self.mpg_frame, \
                                        text="Miles Per Gallon")
        self.mpg = tkinter.StringVar()
        self.mpg_label = tkinter.Label(self.mpg_frame, \
        self.calc_button = tkinter.Button(self.button_frame, \
                                            text="Calculate MPG" , \
        self.quit_button = tkinter.Button(self.button_frame, \
                                            text="Quit", \

        self.error_label=tkinter.Label(self.error_frame, textvariable=self.error)


    #check gallons and miles numbers. If it can be converted, then return it, if not set the errorlabel.
    def checknumber(self, stringvalue, numbername):
            self.error.set(numbername+" is not a number")
            return None
        if to_return<0:
            self.error.set(numbername+" is negative")
            return None
        return to_return

    #the calc_mpg is the callback function for the calc_button    
    def calc_mpg(self):

        gallons = self.checknumber(self.gallons_entry.get(),"Gallons")
        if gallons is None: return

        miles = self.checknumber(self.miles_entry.get(), "Miles")
        if miles is None: return

    #calculate the MPG
        miles_per_gallon = round((miles / gallons),2)

    #update mpg_label

carmpg = MPG()

grand_78 commented: Sorry for the errors, I was in a rush when typing it. Thank you, this did fix my problem. Much appreciated. +0

You use global imported variables locally.

There is no need to pass ScrolledText and Tk to the Scratchpad class's dunder init. This is redundant.

This is the same, but cleaned up:

from tkinter import Tk, END, INSERT
from tkinter.scrolledtext import ScrolledText
from tkinter.filedialog import asksaveasfilename, askopenfilename

class Scratchpad:

    def __init__(self):
        self.display = Tk()
        self.display.title("Onager Text Editor")
        self.display.bind('<F7>', self.save_file)
        self.display.bind('<F5>', self.open_file)

    def create_editor(self):
        self.editing_window = ScrolledText(self.display)
        self.editing_window.configure(fg='gold', bg='blue', insertbackground='cyan',
            height='25', width='70', padx='12', pady='12',
            wrap='word', tabs='48', font='serif 12')

    def save_file(self, event=None):
        name = asksaveasfilename()
        outfile = open(name, 'w')
        contents = self.editing_window.get(0.0, END)

    def open_file(self, event=None):
        name = askopenfilename()
        infile = open(name, 'r')
        contents =
        self.editing_window.insert(INSERT, contents)

def main():
    onager = Scratchpad()

if __name__=='__main__':

Here you are. I hope, this makes you a really good programmer.

states=sorted([(f[i].strip(),f[i+1].strip(),int(f[i+2])) for i in range(0,len(f)-3,3)],key=lambda x:x[2])
print("minimum population:",states[0])
print("maximum population:",states[-1])
j.parkerrrr commented: Thank u very much, I really appreciate it. +0
class Date(object):

    def __init__(self, year, month, day):

    def __add__(self, other):
        if not isinstance(other,Delta):
            raise Exception("can only add Delta object")
        #FIXME handle the calendar 
        return Date(year,month,

    def __str__(self):
        return "("+",".join(map(str,(self.year,self.month,")"

class Delta(object):

    def __init__(self, year, month):
        if not (1<=month<=12) or year<0 or \
        not isinstance(year,int) or not isinstance(month, int):
            raise Exception("invalid Delta parameters")

    def __add__(self, other):
        return other+self

print Delta(year=5, month=6) + Date(2019,5,2)

There is no question.
So I have solved it.


nums=[(int(input("Give me the number numero {}: ".format(i+1)))) for i in range(20)]
print("Lowest: {}\nHighest: {}\nTotal: {}\nAverage: {}".format(min(nums),max(nums),sum(nums),sum(nums)/len(nums)))

I hope that makes you smarter.

I suggest to calculate it in a spreadsheet (excel) before you program it. The first x rows will be the conditions, then every row is a date where a payment is due. The columns will be the variables you are using in the program.

Let me inform you, that this calculation is far from the real world loan calculation. Bicycle-car comparison comes to my mind. Both are vehicles. But this may not matter for you....

[mylist[i:i+3] for i in range(0,len(mylist),3)]
* We create a list of one character strings, which are the button labels and numbers or operations at the same time. 
line 6-11
* We start a loop on button label elements. We interpret an index of a button label element as a row, column index. row= index//4+1 column=index%4
line 13-15, line 19-21, 
* In this loop for each element **begin**
* We create a button, with the following attributes 
    * the actual label element as text 
line 17 text=buttons
    * a function call with the actual label element as a parameter (function not explained here)
line 16 and line 17 'command=cmd '
    * we set the button's grid, to place the button to row and column
line 17 '.grid(row=r, column=c)'
* In this loop for each element **end**
* We create an entry widget  on the first (0th) row and make it span 4 column.
line 22-23

I have python2 so I changed tkinter to Tkinter. I am not a big tkinter expert.

Firstly the code does not work. root.mainloop() or similar is missing. If I put it in, it works.

Secondly. If you have created the code, then there was something on your mind, or not?

Thirdly: I tried to do what I understand you want.

* We create a list of one character strings, which are the button labels and numbers or operations at the same time. 
* We start a loop on button label elements. We interpret an index of a button label element as a row, column index. row= index//4+1 column=index%4
* In this loop for each element **begin**
* We create a button, with the following attributes 
    * the actual label element as text 
    * a function call with the actual label element as a parameter (function not explained here)
    * we set the button's grid, to place the button to row and column
* In this loop for each element **end**
* We create an entry widget  on the first (0th) row and make it span 4 column.

No need to apologize.
If you don't make mistakes, you don't do anything.

Thanks if you've taken an interest but have figured it out: needed to assign a variable to the function.

Better formulated:
Needed to assign a variable to the function's return value.

I do not understand what your checker supposed to do semantically.
What are line 8 and 9 supposed to mean? Especially if you call it with 1.

If your algo is right, then all nonzero elements of the siv will be primes.

You can write a tests to check if the code works properly. Tests can be performed by using isprime function .

There is no use of testing the code on every run. The only case where this is appropriate, if some data is external or random. But that is not the case.

Firstly this is not the mentioned algo. The real one does NOT have an isprime function. That is the main advantage of it.

Secondly it is not slowed down. It is slow. If you are interested, we can discuss it.

Thirdly look up this algo's implementation here:

I do not know a standard for pseudo code. I have read this, and became not smarter.

For a natural language pseaudo code I would write:

asktext = Which sided dice would you like to roll? You can choose a 4-sided dice, a 6-sided dice or a 12-sided dice. Type 0 to exit the loop.
printouttext="The %s-sided dice has rolled to %s"
infinite loop:
    ask the user which dice to roll with asktext
    convert the aswer to integer, store it in sides
    if sides is 0, then exit the loop
    if sides not one of 4,6,12, then continue the loop
    make a random integer between 1 and sides, store it in rolled.
    print out printouttext with sides and rolled substituted

Your 7th line has an error. You need to convert the output of the input function to int. Not the input function itself.
It is an over kill to calculate all the diceroll for all the possible inputs. It is enough to calculate it after the input.
No need for so much elifs...
Randrange is overkill for this...

I fixed this for you:

import random
while True:
    sides = int(input("Which sided dice would you like to roll? You can choose a 4-sided dice, a 6-sided dice or a 12-sided dice. Type 0 to exit the loop."))
    if sides==0:
    if sides not in (4,6,12):
        print("Please input a number 4, 6 or 12")
    rolled = random.randint(1,sides)
    print ("The %s-sided dice has rolled to %s" % (sides,rolled))

Hello Zahra!

I would make a Game class that holds the characters. Then I would make the characters that generates the attributes. The attributes are generated by rolling a dice.

Something like this:

# python 2 code

import random
class Dice(object):
    def __init__(self,sides):
    def roll(self):
        return random.randint(1,self.sides)

class Charachter(object):
    def __init__(self, name):
        self.attributes={"strength":0, "skill":0}

    def reset_attributes(self):
        for k in self.attributes.keys():

    def __str__(self):
         for k,v in self.attributes.iteritems():
              ret+="%s : %s\n" % (k,v)
         return ret

class Game(object):
    def __init__(self):

    def generate_charachters(self):

if __name__ == "__main__":
    for ch,attrs in g.charachters.iteritems():
         print ch
         print attrs

Next I would make a method in the charachter class that outputs the character data in some standardized way, possible a dictionary containing name and a dictionary of attributes. Then I would make the game class generate the two characters and save the data of the characters into a file.

The next move is to load the characters from this file...

In python 3 print is a function.

You should write: print("Hello, World")

Or better:

class Importedvalues(object): 
    def __init__(self,inputstring):
        for statement in inputstring.split("&"):


print i.variable1
print i.varible2
print i.varible4

I wouldn't pollute the main namespace with arbitrary variables. I provided this in comments.

First you have to convert the input string into a dictionary.
Then you can update some objects namespace with this dictionary.

class Importedvalues(object): pass


for statement in vs.split("&"):


print i.variable1
print i.varible2
print i.varible4

#print variable1
#print varible2
#print varible4

Your function does what zip builtin function does. Just much more inefficiently.

It takes iterables, and return a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
The returned list is truncated in length to the length of the shortest argument sequence.

I suggest just to use zip, or itertools.izip


To all: That would have meant, that deep in "ancient" history of computers. Mistake has been made to let people somehow access binary code; or at least read it. Is that true?

Yes. By Neumann. See:
It is not a mistake. It is a decision that has consequences.

RikTelner commented: Good answer +1

Offtopic post, in the offtopic topic.

As others pointed out, software is always part of larger system which involves interfaces to other softwares, people, and in the end the mother nature.

In my opinion hacking is: Persuade a system to do something not normal, something out of ordinary, something not meant to do.

If we extend the meaning the system to every conceivable system in the world, then we can see that human activity sums up pretty much as hacking the world.

This activity is so extensive and so ancient, that sheer meaning of natural is a matter of opinion today. We perceive our artifical systems as fundamental. They change so rapidly that consensus is impossible.

We are master hackers. There is always a better hacker, then you.

As an exercise please deny the following statement:
There is a moment is every woman's life, when she wants to do something forbidden.

Just joking.

You wanted to write: n!=1 and n!=2

Because for every number n the following is true:
n!=1 or n!=2

Clear thinking?

Gribouillis commented: indeed +14
aVar++ commented: Thanks mate :) +4

Without knowing what the problem at hand is...

The preferred way of reading a file line by line is:

with open('filename.txt') as fp:
    for line in fp:

Your code opens program0.4.txt, reads everything into a string. Then you split this string by space and enter. So your line variable will iterate over the nonspace characters of the file in the end. I suppose, this is not what you wanted.

Oh no. It only works if all numbers between 2 and the number of sides -2 are not divider of number of sides.

So it does not work on hexagon.

And I did not do the math correctly.

star_angle=interior_angle - (sequence_diff*180-(sequence_diff-1)*interior_angle)

If you change sequence_diff to 1, then you get the polygon, as expected.