If loop in tkinter - button pressed - if-statement

How to get tkinter to enter the if loop when button pressed to print? I do not want the print command to be in the button function.
Code:
from tkinter import *
class Player:
N = 0
def __init__(self, name, points):
# instance variables goes here
self.name = name
self.score = points
# increment class variable
Player.N = Player.N+1
class G_501:
def __init__(self, players=[]):
self.NoPlayers = len(players)
print("Number of players",self.NoPlayers)
Spillere = []
Score = []
Runde = 0
for i in range(0, len(players)):
P = Player(players[i], 501)
print("Player", Player.N, P.name, "- Point:", P.score)
Spillere.append(P.name)
Score.append(P.score)
Score = list(map(int, Score))
root = Tk()
c = [False]
def half_bull(c, event=None):
c.append(True)
return c
b1 = Button(root, text="Half Bull", bg="green", fg="black", command=lambda c=c: half_bull(c))
b1.pack()
print(c)
if c[-1] == True:
print("Fedt")
root.mainloop()
S = G_501(["Chr"])
Only need help with the tkinter part... Thanks!

Related

Car park cost calculator python 2.7 Tkinter

Im very new to python and im currently trying to create gui for a program that calculates the cost of parking. When running the code there are no errors but the program doesn't produce a label with the calculated cost. I also want it to produce a message asking for a valid input code if the letters C,D or V are not entered into the entry boxes. Any help in where im going wrong would be appreciated! I know the layout doesn't look good at the moment i'm going to go back and fix the placement of labels afterwards its more getting core basics of the code working that i'm struggling with.
-- coding: cp1252 --
import Tkinter as tk
import re
from functools import partial
def Vehicle(label_result, n1, n2):
Vehicle = Vehicletypeentrytext.get()
Vehicle_upper = Vehicle.upper()
if not re.match("^[C,V,D]*$", Vehicle_upper):
label_result.config(text="Please input valid vehicle code")
return
elif Vehicle_upper=='C':
def carcost(label_result, n1, n2):
num1 = (n1.get())
num2 = (n2.get())
result = (int(num2)-int(num1))+1
label_result.config(text="Cost for Parking is %d" % result)
return
elif Vehicle_upper=='V':
def vancost(label_result, n1, n2):
num1 = (n1.get())
num2 = (n2.get())
result = (int(num1)-int(num2))+2
label_result.config(text="Cost for Parking is%d" % result)
return
elif Vehicle_upper=='D':
def disabledcost(label_result, n1, n2):
num1 = (n1.get())
num2 = (n2.get())
result = (int(num1)-int(num2))
label_result.config(text="Cost for Parking is%d" % result)
return
root = tk.Tk()
root.geometry('800x600')
root.title('Simple Calculator')
number1 = tk.StringVar()
number2 = tk.StringVar()
Title = tk.Label(root, text="SHORTSTAY CARPARK PAYMENT").grid(row=0, column=2)
Price = tk.Label(root, text = "1 hour = $2.00 / $3.00 / $1.00\n2 hour = $3.00 / $4.00 / $2.00\n3 hour = $4.00 / $5.00 / $3.00\n4 hour = $5.00 / $6.00 / $4.00\n").grid(row=1, column=0)
Vehicletypeentrytext = tk.StringVar()
Vehicletypelabel = tk.Label(root, text = 'Enter your Vehicle type:\nC for Car\tV for Van\tD for Disabled driver').grid(row=2, column=3)
Vehicletypeentry = tk.Entry(root, textvariable=Vehicletypeentrytext).grid(row=4, column=3)
labelNum1 = tk.Label(root, text="Enter Time in:").grid(row=5, column=0)
labelNum2 = tk.Label(root, text="Enter Time Out:").grid(row=6, column=0)
entryNum1 = tk.Entry(root, textvariable=number1).grid(row=5, column=2)
entryNum2 = tk.Entry(root, textvariable=number2).grid(row=6, column=2)
labelResult = tk.Label(root)
labelResult.grid(row=7, column=2)
Vehicle = partial(Vehicle, labelResult, number1, number2)
buttonCal = tk.Button(root, text="Calculate", command=Vehicle).grid(row=7, column=0)
root.mainloop()
You were calling functions inside def Vehicle(label_result, n1, n2) which isn't adding anything to your script so it preventing the result to display as a Label.No need to create function inside your if elif statement.check my edit on your function def Vehicle(label_result, n1, n2)
import Tkinter as tk
import re
from functools import partial
def Vehicle(label_result, n1, n2):
Vehicle = Vehicletypeentrytext.get()
Vehicle_upper = Vehicle.upper()
if not re.match("^[C,V,D]*$", Vehicle_upper):
label_result.config(text="Please input valid vehicle code")
return
elif Vehicle_upper == 'C':
num1 = (n1.get())
num2 = (n2.get())
result = (int(num2) - int(num1)) + 1
label_result.config(text="Cost for Parking is %d" % result)
return
elif Vehicle_upper == 'V':
num1 = (n1.get())
num2 = (n2.get())
result = (int(num1) - int(num2)) + 2
label_result.config(text="Cost for Parking is%d" % result)
return
elif Vehicle_upper == 'D':
num1 = (n1.get())
num2 = (n2.get())
result = (int(num1) - int(num2))
label_result.config(text="Cost for Parking is%d" % result)
return
root = tk.Tk()
root.geometry('800x600')
root.title('Simple Calculator')
number1 = tk.StringVar()
number2 = tk.StringVar()
Title = tk.Label(root, text="SHORTSTAY CARPARK PAYMENT").grid(row=0, column=2)
Price = tk.Label(root, text = "1 hour = $2.00 / $3.00 / $1.00\n2 hour = $3.00 / $4.00 / $2.00\n3 hour = $4.00 / $5.00 / $3.00\n4 hour = $5.00 / $6.00 / $4.00\n").grid(row=1, column=0)
Vehicletypeentrytext = tk.StringVar()
Vehicletypelabel = tk.Label(root, text = 'Enter your Vehicle type:\nC for Car\tV for Van\tD for Disabled driver').grid(row=2, column=3)
Vehicletypeentry = tk.Entry(root, textvariable=Vehicletypeentrytext).grid(row=4, column=3)
labelNum1 = tk.Label(root, text="Enter Time in:").grid(row=5, column=0)
labelNum2 = tk.Label(root, text="Enter Time Out:").grid(row=6, column=0)
entryNum1 = tk.Entry(root, textvariable=number1).grid(row=5, column=2)
entryNum2 = tk.Entry(root, textvariable=number2).grid(row=6, column=2)
labelResult = tk.Label(root)
labelResult.grid(row=7, column=2)
Vehicle = partial(Vehicle, labelResult, number1, number2)
buttonCal = tk.Button(root, text="Calculate", command=Vehicle).grid(row=7,
column=0)
root.mainloop()

Object not iterable when assigning to a list

I am coding a 2048 game via pygame. below is the relevant section of my code:
class Data():
def __init__(self):
self.data = getnull()
self.score = 0
def updatesprites(self): # EXP
spritelist = [[],[],[],[]]
for count in range(4): # for row loop
for i in range(4): # per column loop
if self.data[count][i] != 0:
spritelist[count]+= newSprite(str(self.data[count] [i])+".png") # error occurs here
spritelist[count][i].move(15 + i*115, 15 + count*115)
showSprite(spritelist[count][i])
class newSprite(pygame.sprite.Sprite):
def __init__(self,filename):
pygame.sprite.Sprite.__init__(self)
self.images=[]
self.images.append(loadImage(filename))
self.image = pygame.Surface.copy(self.images[0])
self.currentImage = 0
self.rect=self.image.get_rect()
self.rect.topleft=(0,0)
self.mask = pygame.mask.from_surface(self.image)
self.angle = 0
def addImage(self, filename):
self.images.append(loadImage(filename))
def move(self,xpos,ypos,centre=False):
if centre:
self.rect.center = [xpos,ypos]
else:
self.rect.topleft = [xpos,ypos]
----------------Main-------------------
from functions import *
from config import *
from pygame_functions import *
import pygame
screenSize(475,475) # call screen init
gameboard = newSprite("game board.png") # createboard
showSprite(gameboard)
game = Data()
game.updatesprites()
while True:
pass
when game.updatesprites() is called, "newSprite object is not iterable" error is raised in function Data.updatesprites
+ concatenates lists and strings, and adds numbers.
What you are trying to do, is to add an element to a list.
This is done as follows:
li.append(element) # adds the element to the end of the list
Or in your case:
spritelist[count].append(newSprite(str(self.data[count][i]) + ".png"))
Another solution: You could create a new type, that lets you add elements the way you were trying to:
class UglyList(list):
def __iadd__(self, other):
self.append(other)
You'd need to change another line here:
spritelist = [UglyList() for i in range(4)]

check entry inputs in tkinter using a function

I trying to create physics calculator using python tkinter but I find it quite difficult. I have done this calculator in Command line interface but I a bit different with tkinter. basically, I have 5 entry boxes and above each one of them a button. the user will insert values in three of them and should press the button on top of each unknown value to make the calculation and get the result. my main issue is how can I create a function that evaluates the inputs in my entry boxes and make the calculation then print the results inside the entry box. I made some coding but unfortunately the operation is not working due to few mistakes.
here is my coding part:
from Tkinter import *
import math
class calculator():
def is_positive_number(number): # validation function
if number <= 0:
return False
else :
return True
def value_of_time(prompt):
while True: # loop command for time
try:
valid = False
while not valid:
value = float((prompt))
if is_positive_number(value):
valid = True
return value
else :
valid = False
print ('I donot know what is happening')
except ValueError:
print("Oops, unfortunately this is a wrong input, please try again.")
#better try again... Return to the start of the loop
continue
else:
#value was successfully parsed!
#we're ready to exit the loop.
break
def input_of_box(prompt):
while True: # loop for initial velocity
try:
value = float(input(prompt))
return value
except ValueError:
print("Oops, we are you not typing a number, please try again.")
#better try again... Return to the start of the loop
continue
else:
#value was successfully parsed!
#we're ready to exit the loop.
break
# def minput(numberofinput):
if numberofinput == 1:
t = value_of_time("Enter the time that takes an object to accelerate in seconds:")
return
elif numberofinput == 2:
u = input_of_box("Enter the initial velocity in m/s:")
return
elif numberofinput == 2:
v = input_of_box("Enter the final velocity in m/s:")
return
def my_calculation(mvariables): # this function is to operate the calculation
if mvariables == 1:
a = (v-u) /(t)
mentery1 = a
return
elif mvariables == 2:
v = u + a*t
mentery2 = v
return
elif mvariables == 3:
u = a*t - v
mentery3 = t
elif mvariables == 4:
t = (v - u)/a
mentery3 = t
return
elif mvariables == 5:
s = (v**2-u**2)/2*a
mentery4 = s
else:
print ('there is an error')
cal = Tk()
cal.configure(background='sky blue')
a = StringVar()
u = StringVar()
v = StringVar()
t = StringVar()
s = StringVar()
cal.geometry('650x420+350+225')
cal.title('Main Menu')
# here we start greating buttons and entry boxes
m_label = Label(text='Calculator',fg = 'Navy', font=("Helvetica", 20,"bold italic"), bg='sky blue')
m_label.pack()
button1 = Button(cal,text='A',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(1))
button1.place(x=92,y=210)
mentery1 = Entry(cal, textvariable = a ,width=10,bd =3)
mentery1.place(x=82,y=240)
button2 = Button(cal,text='U',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(3))
button2.place(x=192,y=210)
mentery2 = Entry(cal, textvariable = u ,width=10,bd =3)
mentery2.place(x=182,y=240)
button3 = Button(cal,text='V',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(2))
button3.place(x=292,y=210)
mentery3 = Entry(cal, textvariable = v ,width=10,bd =3)
mentery3.place(x=282,y=240)
button4 = Button(cal,text='T',fg='white',bg='dark green',bd =3, width=4,command= lambda : my_calculation(4))
button4.place(x=392,y=210)
mentery4 = Entry(cal, textvariable = t ,width=10,bd =3)
mentery4.place(x=382,y=240)
button5 = Button(cal,text='S',fg='white',bg='dark green',bd =3, width=4,command= lambda : my_calculation(5))
button5.place(x=492,y=210)
mentery5 = Entry(cal, textvariable = s , width=10,bd =3)
mentery5.place(x=482,y=240)
# end of button commands
app = calculator()
app.mainloop()
For validating the input, do the following:
def returnValidatedInput(entry):
value = entry.get() # Get the text in the 'entry' widget
evaluation = eval(value) # Evaluate 'value'
return evaluation
And for inserting the answers into the entries (it's not called printing the answers into the entries):
def insertAnswer(entry, answer):
entry.delete(0, 'end') # Be sure the entry is empty, if it is not, clear it
entry.insert(END, str(answer)) # Insert the answer into the 'entry' widget.

Attribute error occurs when I run my GUI code in Python. Python gives me no information as to what the error is or what is causing it

This is my code and when i try to run it and use it by entering numbers into the entry fields, an attribute error occurs when i try to call on the entry variable. This is the message that appears:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in call
return self.func(*args)
File "F:\HomeWork\Yr13\Extended Project\Notepad++\Python27\Programs\GUI{c} menu+check+gen+Nth.py", line 224, in OnGenButtonClick
n= str(Prime_Generation(Prime_Gen.entryVariable5.get(),Prime_Gen.entryVariable6.get()))
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1845, in getattr
return getattr(self.tk, attr)
AttributeError: entryVariable5
any help would be greatly appreciated.
i have stuck on this problem for three days and have tried getting around the problem by using different functions and names and the error still occurs
import Tkinter
from Tkinter import *
import math
def SoS(limit):
numbers = range(3, limit+1, 2)
half = (limit)//2
initial = 4
for step in xrange(3, limit+1, 2):
for i in xrange(initial, half, step):
numbers[i-1] = 0
initial += 2*(step+1)
if initial > half:
plist = [2] + filter(None, numbers)
return plist
break
def S(m):
sieve = [True] * m
for i in xrange(3,(int(m**0.5)+1),2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((m-i*i-1)/(2*i)+1)
plist = [2] + [i for i in xrange(3,m,2) if sieve[i]]
return plist
def OTS(n):
n, correction = n-n%6+6, 2-(n%6>1)
sieve = [True] * (n/3)
for i in xrange(1,(int(n**0.5)/3)+1):
if sieve[i]:
k=3*i+1|1
sieve[ k*k/3 ::2*k] = [False] * ((n/6-k*k/6-1)/k+1)
sieve[k*(k-2*(i&1)+4)/3::2*k] = [False] * ((n/6-k*(k-2*(i&1)+4)/6-1)/k+1)
plist = [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]
return plist
def is_prime(num):
if num <= 3:
if num <= 1:
return False
return True
if not num % 2 or not num % 3:
return False
for i in xrange(5, int(num ** 0.5) + 1, 6):
if not num % i or not num % (i + 2):
return False
return True
def is_prime_multiple(Lower,Upper):
NumberList = dict()
if Lower%2 == 1:
for i in xrange(Lower, Upper,2):
NumberList[i] = is_prime(i)
else:
for i in xrange(Lower-1,Upper,2):
NumberList[i] = is_prime(i)
NumberList[1] = False
return [i for i in NumberList if NumberList[i] == True]
def Prime_Generation(L,U):
Lower = int(L)
Upper = int(U)
if Lower == 1:
if Upper < 92:
print SoS(Upper)
if Upper >= 92 and Upper < 2250:
print S(Upper)
if Upper >= 2250 :
print OTS(Upper)
else:
print sorted(is_prime_multiple(Lower,Upper))
def factors(n):
f = 3
fs = []
while n % 2 == 0:
fs.append(2)
n /= 2
while f*f <= n:
while n % f == 0:
fs.append(f)
n /= f
f += 2
if n > 1:
fs.append(n)
return fs
def Prime_Checker(N):
NStr = str(N)
N = int(N)
Nfs = factors(N)
for i in Nfs:
if i != N:
NfsStr = str(Nfs).strip('[]')
resultb = [NStr,' is not a prime. The prime factors of ',NStr,' are ',NfsStr]
return resultb.join()
else:
return N,' is a prime. The prime factors of ',N ,' are ',N
def PrimeFinderLamda(n,limit):
nums = range(3,limit,2)
for i in range(2, int(limit**0.5)):
nums = filter(lambda x: x == i or x % i, nums)
return [2]+nums
def NthPrime(N):
N = int(N)
Lower = 1
limit = N*N
if N == 1:
return 2
else:
return PrimeFinderLamda(N,limit)[N-1]
class Prime_app_tk(Tkinter.Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def Prime_Gen_Win(self):
Prime_Gen = Toplevel()
Prime_Gen.grid()
Prime_Gen.labelVariable3 = StringVar()
Title_label2 = Label(Prime_Gen,textvariable=Prime_Gen.labelVariable3,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label2.grid(column=0,row=0,columnspan=4)
Prime_Gen.labelVariable3.set(u"Please enter the upper and lower limits of the prime number generation")
Prime_Gen.labelVariable4 = StringVar()
SubTitle_label1 = Label(Prime_Gen,textvariable=Prime_Gen.labelVariable4,fg="black",bg="white")
SubTitle_label1.grid(column=0,row=1,columnspan=4)
Prime_Gen.labelVariable4.set(u"(Please enter values no greater than 10 million)")
Prime_Gen.entryVariable5 = StringVar()
Prime_Gen.entry = Entry(Prime_Gen,textvariable=Prime_Gen.entryVariable5)
Prime_Gen.entry.grid(column=0,row=4)
Prime_Gen.entryVariable5.set(u"Lower.")
Prime_Gen.entryVariable6 = StringVar()
Prime_Gen.entry = Entry(Prime_Gen,textvariable=Prime_Gen.entryVariable6)
Prime_Gen.entry.grid(column=0,row=5)
Prime_Gen.entryVariable6.set(u"Upper.")
Genbutton = Button(Prime_Gen,text=u"Generate !",command=self.OnGenButtonClick #placing and aesthetics of button
,bg="yellow",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
Genbutton.grid(column=0,row=6)
scrollbar = Scrollbar(Prime_Gen)
scrollbar.grid(column=1,row=8,sticky="ns")
Prime_Gen.Result_label = Text(Prime_Gen, yscrollcommand=scrollbar.set
,fg="blue",bg="white",wrap=WORD
,width=100,relief = SUNKEN)
Prime_Gen.Result_label.grid(column=0,row=8,columnspan=2)
scrollbar.config(command=Prime_Gen.Result_label.yview)
Prime_Gen.labelVariable = StringVar()
SubTitle_label = Label(Prime_Gen,textvariable=Prime_Gen.labelVariable,fg="black",bg="white")
SubTitle_label.grid(column=0,row=9,columnspan=4)
Prime_Gen.labelVariable.set(u"To see full list please click on the results\n and use the up and down arrows to scroll through the list")
Prime_Gen.grid_columnconfigure(0,weight=1)
Prime_Gen.resizable(True,True)
Prime_Gen.update()
Prime_Gen.geometry(Prime_Gen.geometry())
Prime_Gen.entry.focus_set()
Prime_Gen.entry.selection_range(0, Tkinter.END)
def OnGenButtonClick(Prime_Gen):
n= str(Prime_Generation(Prime_Gen.entryVariable5.get(),Prime_Gen.entryVariable6.get()))
Prime_Gen.Result_label.insert(END,"\nPrimes Found\n")
Prime_Gen.Result_label.insert(END,n)
Prime_Gen.entry.focus_set()
Prime_Gen.entry.selection_range(0, Tkinter.END)
def Prime_Check_Win(self):
Prime_Check = Toplevel()
Prime_Check.grid()
Prime_Check.labelVariable8 = StringVar()
Title_label3 = Label(Prime_Check,textvariable=Prime_Check.labelVariable8,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label3.grid(column=0,row=0,columnspan=4)
Prime_Check.labelVariable8.set(u"Please enter a Number to be checked for primality")
Prime_Check.labelVariable9 = StringVar()
SubTitle_label3 = Label(Prime_Check,textvariable=Prime_Check.labelVariable9,fg="black",bg="white")
SubTitle_label3.grid(column=0,row=1,columnspan=4)
Prime_Check.labelVariable9.set(u"(Please enter values no greater than 10 million)")
Prime_Check.entryVariable = StringVar()
Prime_Check.entry = Entry(Prime_Check,textvariable=Prime_Check.entryVariable)
Prime_Check.entry.grid(column=0,row=2)
Prime_Check.entryVariable.set(u"Enter Number here.")
Checkbutton = Button(Prime_Check,text=u"Check !",command=self.OnCheckButtonClick
,bg="blue",fg="white",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
Checkbutton.grid(column=0,row=4)
Prime_Check.labelVariable10 = StringVar()
Result_label2 = Message(Prime_Check,textvariable=Prime_Check.labelVariable10
,anchor="w",fg="blue",bg="white"
,width=500,relief = SUNKEN,padx=3,pady=3)
Result_label2.grid(column=0,row=5,columnspan=2,rowspan=100)
Prime_Check.labelVariable10.set(u"Hello")
Prime_Check.grid_columnconfigure(0,weight=1)
Prime_Check.resizable(True,False)
Prime_Check.update()
Prime_Check.geometry(Prime_Check.geometry())
Prime_Check.entry.focus_set()
Prime_Check.entry.selection_range(0, Tkinter.END)
def OnCheckButtonClick(Prime_Check):
Prime_Check.labelVariable10.set(Prime_Checker(Prime_Check.entryVariable.get())) #Had to call on prime gen and display results
Prime_Check.entry.focus_set()
Prime_Check.entry.selection_range(0, Tkinter.END)
def Nth_Prime_Win(self):
Nth_Prime = Toplevel()
Nth_Prime.grid()
Nth_Prime.labelVariable12 = StringVar()
Title_label = Label(Nth_Prime,textvariable=Nth_Prime.labelVariable12,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label.grid(column=0,row=0,columnspan=4)
Nth_Prime.labelVariable12.set(u"Please enter the Nth prime you would like to find")
Nth_Prime.labelVariable13 = StringVar()
SubTitle_label = Label(Nth_Prime,textvariable=Nth_Prime.labelVariable13,fg="black",bg="white")
SubTitle_label.grid(column=0,row=1,columnspan=4)
Nth_Prime.labelVariable13.set(u"(Please enter values no greater than 664579")
Nth_Prime.entryVariable = StringVar()
Nth_Prime.entry = Entry(Nth_Prime,textvariable=Nth_Prime.entryVariable)
Nth_Prime.entry.grid(column=0,row=4)
Nth_Prime.entryVariable.set(u"Enter Number here.")
Genbutton = Button(Nth_Prime,text=u"Generate !",command=self.OnButtonNthClick
,bg="green",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
Genbutton.grid(column=0,row=5)
Nth_Prime.labelVariable14 = StringVar()
Result_label = Message(Nth_Prime,textvariable=Nth_Prime.labelVariable14
,anchor="w",fg="blue",bg="white"
,width=1000,relief = SUNKEN,justify=LEFT,padx=3,pady=3)
Result_label.grid(column=0,row=6,columnspan=2,rowspan=100)
Nth_Prime.labelVariable14.set(u"Hello")
Nth_Prime.grid_columnconfigure(0,weight=1)
Nth_Prime.resizable(False,False)
Nth_Prime.update()
Nth_Prime.geometry(Nth_Prime.geometry())
Nth_Prime.entry.focus_set()
Nth_Prime.entry.selection_range(0, Tkinter.END)
def OnButtonNthClick(Nth_Prime):
Nth_Prime.labelVariable14.set(NthPrime(Nth_Prime.entryVariable.get()))
Nth_Prime.entry.focus_set()
Nth_Prime.entry.selection_range(0, Tkinter.END)
def initialize(self):
self.grid()
self.labelVariable1 = StringVar()
Title_label1 = Label(self,textvariable=self.labelVariable1,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label1.grid(column=0,row=0,columnspan=4)
self.labelVariable1.set(u"Welcome to the Prime Program")
self.labelVariable2 = StringVar()
SubTitle_label = Label(self,textvariable=self.labelVariable2,fg="black",bg="white")
SubTitle_label.grid(column=0,row=1,columnspan=4)
self.labelVariable2.set(u"(Please select the function you would like to use)")
PrimeGenbutton = Button(self,text=u"Find Primes between 2 limits !",command=self.Prime_Gen_Win
,bg="yellow",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
PrimeGenbutton.grid(column=0,row=3)
PrimeCheckbutton = Button(self,text=u"Check if a number is prime !",command=self.Prime_Check_Win
,bg="blue",fg="white",relief=RAISED,padx=14,pady=10
,activebackground="red",activeforeground="white")
PrimeCheckbutton.grid(column=0,row=4)
NthPrimebutton = Button(self,text=u"Find the Nth prime !",command=self.Nth_Prime_Win
,bg="green",relief=RAISED,padx=35,pady=10
,activebackground="red",activeforeground="white")
NthPrimebutton.grid(column=0,row=5)
self.grid_columnconfigure(0,weight=1)
self.resizable(False,False)
self.update()
self.geometry(self.geometry())
if __name__ == "__main__":
app = Prime_app_tk(None)
app.title('Prime Program')
app.mainloop()
There's no quick fix for your code. It attempts to be object-oriented, but is doing so incorrectly. You need to properly define your methods, and should also adhere to PEP8 naming conventions -- specifically, methods and functions should start with a lowercase, and classes should start with an uppercase. Because you don't follow PEP8, and because of the odd way you use Prime_Gen to mean different things at different times, your code is incredibly hard to understand.
The crux of the problem is that inside OnGenButtonClick, Prime_Gen is not what you think it is. It is an instance of Prime_app_tk rather than the value that you set the local variable Prime_Gen to in Prime_Gen_Win. Thus, any attributes you assigned to the original Prime_Gen don't exist in this other Prime_Gen.
The reason is that the button is defined like this:
Genbutton = Button(..., command=self.OnGenButtonClick, ...)
In this context, self is the instance of Prime_app_tk, so that becomes the parameter passed to OnGenButtonClick. Inside that function you call the parameter Prime_Gen, in spite of the universal convention to name it self. This causes confusion in your code, because you also have a local variable named Prime_Gen in the code that creates the toplevel window.

Cannot Pool.map() function because of UnpickleableError?

So I am trying to multi process function F. Which is accessed by a button press with tkinter.
def f(x):
global doom,results,info
doom = doom + 1
if check(x) == True:
results.add(x)
info.append(get_column_number(x))
j.step(1)
texx = "1/"+doom
s.configure(text=texx)
root.update()
The function is called within a function like so:
def dojob():
index = ['URLS'...]
pool = Pool(processes=4)
s.configure(text="Shifting Workload to cores..")
root.update()
pool.map(f, index)
The button is inside root window.
I get the following error:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 808, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 761, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Python27\lib\multiprocessing\pool.py", line 342, in _handle_tasks
put(task)
UnpickleableError: Cannot pickle <type 'tkapp'> objects
I do not even know what a pickle does? Help?
Here is the complete code:
from Tkinter import *
from ttk import *
from tkMessageBox import showinfo
from multiprocessing import Pool
import random
emails = set()
import urllib2
import urllib2 as urllib
########
CONSTANT_PAGECOUNT = 20
######
def f(x):
global doom,emails,info
doom = doom + 1
if check(x) == True:
print "",
emails.add(x)
info.append(get_column_number(x))
j.step(1)
texx = "Sk1nn1n "+str(doom)+'/'+str(CONSTANT_PAGECOUNT)+""
s.configure(text=texx)
root.update()
return 0
def f(x):
print ""
def showFile(site,info):
top = Toplevel()
top.title('Sites')
x = Text(top)
x.pack()
i=0
for site_url in site:
x.insert(END,site_url)
i=i+1
def get_column_number(url):
return True
def check(url):
return True
def getgoogleurl(search,siteurl=False,startr=0):
if siteurl==False:
return 'http://www.google.com/search?q='+urllib2.quote(search)+'&start='+str(startr)+'&oq='+urllib2.quote(search)
else:
return 'http://www.google.com/search?q=site:'+urllib2.quote(siteurl)+'%20'+urllib2.quote(search)+'&oq=site:'+urllib2.quote(siteurl)+'%20'+urllib2.quote(search)
def getgooglelinks(search,siteurl=False,startr=0):
#google returns 403 without user agent
headers = {'User-agent':'Mozilla/11.0'}
req = urllib2.Request(getgoogleurl(search,siteurl,startr),None,headers)
site = urllib2.urlopen(req)
data = site.read()
site.close()
#no beatifulsoup because google html is generated with javascript
start = data.find('<div id="res">')
end = data.find('<div id="foot">')
if data[start:end]=='':
#error, no links to find
return False
else:
links =[]
data = data[start:end]
start = 0
end = 0
while start>-1 and end>-1:
#get only results of the provided site
if siteurl==False:
start = data.find('<a href="/url?q=')
else:
start = data.find('<a href="/url?q='+str(siteurl))
data = data[start+len('<a href="/url?q='):]
end = data.find('&sa=U&ei=')
if start>-1 and end>-1:
link = urllib2.unquote(data[0:end])
data = data[end:len(data)]
if link.find('http')==0:
links.append(link)
return links
def rip(results=15,accuracy=16):
global e
keyword = ''+str(e.get())
if keyword.strip()=="":
s.configure(text="Please enter a keyword")
root.update()
return 0
linklist = []
counter = 0
doom = 0
while counter < results:
links = getgooglelinks(keyword,startr=counter)
for link in links:
if len(linklist) > CONSTANT_PAGECOUNT:
s.configure(text="Proccessing..")
root.update()
return linklist
else:
doom = doom + 1
linklist.append(link)
texx = str(doom)+"/"+str(CONSTANT_PAGECOUNT)
s.configure(text=texx)
root.update()
root.update()
counter = counter+accuracy
return linklist
def flip():
global e
emails = set()
info = []
keyword = ''+str(e.get())
if keyword.strip()=="":
s.configure(text="Please enter a keyword")
root.update()
return 0
s.configure(text="Generating index..")
root.update()
doom = -1
index = rip(CONSTANT_PAGECOUNT,10)
if 1:
try:
pool = Pool(processes=4)
#s.configure(text="Shifting Workload to cores..")
#root.update()
pool.map(f, index)
pool.close()
except:
print "The errors there.."
j.config(value=CONSTANT_PAGECOUNT)
if len(emails) > 0:
filepath='relavant_list_'+str(random.randint(1,9999))+'.emList.txt'
#print len(emails),
#print "emails found."
ggg = open(filepath,'a+')
for x in emails:
ggg.write(x+"\n")
showinfo(
str(len(emails))+" key word related sites found!",
" sites are saved in "+str(filepath)
)
showFile(emails,info)
s.configure(text=filepath)
else:
s.configure(text='No related sites found : (')
if __name__ == '__main__':
### CONSTANTS
version = '1.0'
### END CONSTANTS
root = Tk()
root.title('Program v'+version)
s = Style()
s.theme_use('default')
#print s.theme_names()
s.configure("black.Horizontal.TProgressbar", foreground='blue', background='blue')
j = Progressbar(root, style="black.Horizontal.TProgressbar", orient="vertical", length=200, mode="determinate", maximum=CONSTANT_PAGECOUNT, value=0)
j.pack(side='right',fill='y')
f = Frame(root)
x = Frame(f)
e = Entry(x,width=51)
s = Label(x,width=50,anchor='center',text='Waiting for task..')
Button(f,text='Generate List!',width=50,command=flip).pack(fill='both',expand=True)
s.pack(side='bottom',fill='y',expand=True)
e.pack(side='top',fill='both',expand=True)
x.pack(side='top',fill='y',expand=True)
f.pack(side='left',expand=True,fill="both")
root.mainloop()
You are leaking a tkinter object. Most likely because you are trying to update the interface from another process with the last line of f()
Update based on code
You have a name collision between your function f() and a variable f in your __main__ which gets assigned to your main window and causes the tkapp pickle error. Rename the function to def myfunc() or something. Also need to call pool.join() after pool.close()