these two functions are not working as args in the lamba function
which is calculating the price of the sweets
def mysweets():
b = v.get( ) # get the value of v set
cost=int(mysweets_price_list[b]) #price_display
print(cost)
def quantity_sweets():
q = int(spinbox1.get())
print(q)
price = lambda b, q : b * q # final price to be displayed in myLabel_3
print(price(b, q))
I have tried nested functions but they are not working, help please
anyone
from tkinter import *
myGui = Tk()
myGui.geometry('450x450+200+200')
myGui.title('Auto Sweet Dispenser')
price_display = ""
b = 0
#a = 0
q = 0
mysweets_price_list = {1 :9.00,
2 :7.50,
} # dict for the sweet prices
def mysweets():
b = v.get( ) # get the value of v set
cost=int(mysweets_price_list[b]) #price_display
print(cost)
def quantity_sweets():
q = int(spinbox1.get())
print(q)
price = lambda b, q : b * q # final price to be displayed in myLabel_3
print(price(b, q))
v =IntVar()
price =IntVar()
v.set(1)
myLabel = Label(myGui,text = 'Choose your sweets',font = 14, fg ='brown').place(x=140,y=55)#grid(row=3,column=10,sticky = 'e')
myRadio_1 = Radiobutton(myGui,text = 'Mints',variable = v, value = 1, command = mysweets).place(x= 160, y = 100)
myRadio_2 = Radiobutton(myGui,text = 'Nut log',variable = v, value = 2, command = mysweets).place(x= 160, y = 120)
myLabel_2 = Label(myGui,text = 'Select Quantity',font = 12, fg ='brown').place(x=160,y=160)#grid(row=3,column=10,sticky = 'e')
myLabel_3 = Label(myGui,textvariable = price ,font = "Times 14 bold",width = 14, fg ='white', bg= 'blue' ,relief = RAISED).place(x=160,y=220)#grid(row=3,column=10,sticky = 'e')
spinbox1 = Spinbox(myGui,from_=1,to = 6,command = quantity_sweets, state = NORMAL)
spinbox1.place(x=160,y=180)#
myGui.mainloop()
the code works except that price is not being displayed as the lambda
function is not working.
You don't need lambda here (in general lambda should be extremely rare). You only need a single function to get all the data, do the calculation, and update the Label. Like this:
from tkinter import *
myGui = Tk()
myGui.geometry('450x450+200+200')
myGui.title('Auto Sweet Dispenser')
mysweets_price_list = {1 :9.00,
2 :7.50,
} # dict for the sweet prices
def calculate():
b = v.get( ) # get the value of v set
cost=mysweets_price_list[b] #price
q = int(spinbox1.get()) # get quantity.
final_price = cost * q # final price to be displayed
price.set(final_price)
v =IntVar(value=1) # set initial value to 1
price = IntVar()
Label(myGui,text = 'Choose your sweets',font = 14, fg ='brown').place(x=140,y=55)#grid(row=3,column=10,sticky = 'e')
Radiobutton(myGui,text = 'Mints',variable = v, value = 1, command = calculate).place(x= 160, y = 100)
Radiobutton(myGui,text = 'Nut log',variable = v, value = 2, command = calculate).place(x= 160, y = 120)
Label(myGui,text = 'Select Quantity',font = 12, fg ='brown').place(x=160,y=160)#grid(row=3,column=10,sticky = 'e')
Label(myGui,textvariable = price ,font = "Times 14 bold",width = 14, fg ='white', bg= 'blue' ,relief = RAISED).place(x=160,y=220)#grid(row=3,column=10,sticky = 'e')
spinbox1 = Spinbox(myGui,from_=1,to = 6,command = calculate, state = NORMAL)
spinbox1.place(x=160,y=180)
calculate() # do the calculation at boot
myGui.mainloop()
Also, it's very important to know that if you do name = Widget().place() then the name is set to None and is useless. You need to do
name = Widget()
name.grid() # or pack() or place()
or
Widget().grid() # or pack() or place()
Don't mix those 2 styles! The 2-line style is much better, and what we usually use.
Related
On my page I ask for various things to the user in the form as it's a calculator that does various things, now you see, the thing is if the user does not have the value for bf I want to give the option to calculate with different values, that is why I required is False, so first what I want to archive is that if the form is empty I want to be passed as a 0 or False, how can I archive this?
I have the following form:
class CMForm(forms.Form):
age = forms.DecimalField(max_digits=2, decimal_places=0, min_value=15, max_value=80)
sex = forms.ChoiceField(choices=sex)
pregnant = forms.BooleanField(initial=False, required=False)
lactating = forms.BooleanField(initial=False, required=False)
weight = forms.DecimalField(max_digits=4, decimal_places=1, max_value=635)
height = forms.DecimalField(max_digits=4, decimal_places=1, max_value=272)
bf = forms.DecimalField(label='Body Fat(not required)', help_text='%', required=False, decimal_places=1, min_value=1, max_value=80)
activeness = forms.ChoiceField(choices=activity_level)
units = forms.ChoiceField(choices=units)
this view:
def cmr(request):
a = float(request.GET['age'])
bf = float(request.GET.get('bf', 0))
s = str(request.GET['sex'])
g = 0
if s == 'female':
g = 1
w = float(request.GET['weight'])
h = float(request.GET['height'])
act = str(request.GET['activeness'])
u = str(request.GET['units'])
p = str(request.GET.get('pregnant', 0))
lac = str(request.GET.get('lactating', 0))
dci = 0
bmrm = 10*w+6.25*h-5*a+5
bmrf = 10*w+6.25*h-5*a-161
bmi = round(w/(h/100)**2, 1)
if bf is False:
bf = round(-44.988 + (0.503 * a) + (10.689 * g) + (3.172 * bmi) - (0.026 * bmi**2) + (0.181 * bmi * g) - (0.02 * bmi * a) - (0.005 * bmi**2 * g) + (0.00021 * bmi**2 * a), 1)
tbf = w*(bf/100)
ffm = w*(1-(bf/100))
ffmi = ffm/(h/100)**2
nffmi = ffmi+6.1*(1.8-(h/100))
if p == 'on':
dci = 300
if lac == 'on':
dci = dci+500
if s == 'male':
bmr = dci+bmrm
dcis = bmrm*1.2
dcil = bmrm*1.375
dcim = bmrm*1.55
dciv = bmrm*1.725
dcie = bmrm*1.9
else:
bmr = dci+bmrf
dcis = dci+bmrf*1.2
dcil = dci+bmrf*1.375
dcim = dci+bmrf*1.55
dciv = dci+bmrf*1.725
dcie = dci+bmrf*1.9
context = {'dci': round(int(dci)),
'p': p,
'lac': lac,
'bmr': int(bmr),
'dcis': int(dcis),
'dcil': int(dcil),
'dcim': int(dcim),
'dciv': int(dciv),
'dcie': int(dcie),
'act': act,
'bmi': bmi,
'bf': bf,
'tbf': round(tbf, 1),
'ffm': round(ffm, 1),
'ffmi': round(ffmi, 1),
'nffmi': round(nffmi, 1),
}
return render(request, "calorie_maintenance_result.html", context)
And I get the following error:
could not convert string to float: ''
You can use or; given a string s, s or 0 will evaluate to 0 if s is empty:
s = ''
print(float(s or 0)) # 0.0
s = '123'
print(float(s or 0)) # 123.0
This happens because (in python) x or y returns x if x is true, and y if x is false. Since an empty string is "falsy", '' or 0 is equal to 0.
I have a function that is going to be the main area of this program, but when I add in a new function that needs to be executed by a button, it prevents the window from appearing, or gives out an error. The function I am trying to get to appear after a button press is new_function.
def bowler():
global bowler_win
global batsmen
bowler_win = Toplevel(master)
batsmen_win_2.withdraw()
variable = StringVar(bowler_win)
variable.set(fielding_team[0])
title = Label(bowler_win, text = "Please choose the bowler").grid(row = 0, column = 1)
w = OptionMenu(bowler_win, variable, *fielding_team)
w.grid(row = 1, column = 1)
def ok2():
current_bowler = variable.get()
for players in batting_team:
if players == current_bowler:
fielding_team.remove(current_bowler)
main_play()
button = Button(bowler_win, text="OK", command=ok2).grid(row = 2, column = 1)
#####CODE ABOVE IS ONLY TO SHOW WHERE THE FUNCTION BELOW IS EXECUTED FROM
def main_play():
while innings != 3:
facing_length = len(batsmen)
while over != over_amount or out_full == True or facing_length <= 1:
main_win = Toplevel(master)
bowler_win.withdraw()
ws = Label(main_win, text = " ").grid(row = 1, column = 1)
title = Label(main_win, text = "Current Game").grid(row = 0, column = 1)
score = Label(main_win, text = "Current Score:").grid(row = 2, column = 1)
line = Label(main_win, text = "--------------").grid(row = 1, column = 1)
score = Label(main_win, text = str(runs) + "/" + str(out)).grid(row = 3, column = 1)
line = Label(main_win, text="--------------").grid(row=4, column=1)
cur_bat = Label(main_win, text = "Facing Batsmen: " + batsmen[0]).grid(row = 5, column = 1)
other_bat = Label(main_win, text = "Other Batsmen: " + batsmen[1]).grid(row = 6, column = 1)
current_patner = Label(main_win, text = "Patnership: " + str(partnership_runs)).grid(row = 7, column = 1)
button = Button(main_win, text = "Next Play", command = new_function).grid(row = 8, column = 1) ###THIS IS WHERE THE NEW FUNCTION IS EXECUTED
If I call the function new_function after the button, the main_win window does not appear, this is the same for if I call new_function above the main_play function, the same error occurs.
If I try to nest new_function below the button, I get the error
UnboundLocalError: local variable 'new_func' referenced before assignment
Even though its a function(and I don't have a variable named that)
If anyone can help, that would be amazing
I have created a GUI where you can enter values (x values) manually. If you enter a value x1, trace-method will automatically calculate
f(x1)=x1^2=y1 and mean(y) = (1/5 sum_{i=1}^{5} y_i)
So every time an x-value is entered, the corresponding y-value and mean(y) is calculated. The code below works. If you start it you get:
I would like to remove the initial values 0.0 from some cells. The window should look like this when the code is executed:
To get the desired result, I added at the very end before mainloop()
for i in range(1,5):
y_values[i].set("")
cells[(i,0)].delete(0,END)
where i remove the initial values of certain cells. If you start the code with this change, the program will not work properly anymore. If you enter an x-value, only the corresponding y-value is calculated, but not mean(y).
Do any of you know why the code with y_values[i].set(""), cells[(i,0)].delete(0,END) no longer works correctly and how to solve this problem?
Here is the full Code (from picture 1):
from tkinter import *
import tkinter as tk
root = Tk()
Label(root, text = "x-values",padx = 10).grid(row = 0, column = 0)
Label(root, text = "y-values",padx = 10).grid(row = 0, column = 1)
Label(root, text = "Mean y", padx = 10).grid(row = 0, column = 2)
# Create Variables
x_values, y_values = ["x%d" % x for x in range(5)], ["y%d" % x for x in range(5)]
for i in range (5):
x_values[i], y_values[i] = DoubleVar(), DoubleVar()
mean = DoubleVar()
# Create Table
rows, columns, cells = 5, 2, {}
for i in range(columns):
for j in range(rows):
if i == 0: # x-values that can be entered
b = Entry(root, textvariable=x_values[j])
b.grid(row = j+1, column = i, sticky = W + E)
cells[(j,i)] = b
else: # y-values that are computed by f
b = Label(root, textvariable=y_values[j])
b.grid(row = j+1, column = i, sticky = W + E)
cells[(j,i)] = b
label_mean = Label(root, textvariable = mean).grid(row = 1, column = 2, rowspan = 5)
# compute y-values
def f(name, index, mode):
try:
for i in range(5):
y_values[i].set(x_values[i].get()**2)
except tk.TclError:
pass
# compute mean and standard deviation
def statistic(name, index, mode):
try:
y_sum = 0
for i in range(5):
y_sum += y_values[i].get()
y_normalized = y_sum / 5
mean.set(y_normalized)
except tk.TclError:
pass
# Traces to trigger the above functions
for i in range(5):
x_values[i].trace('w', f)
y_values[i].trace('w', statistic)
mainloop()
Mean is not calculating because it is raising exception when you tried to add None value to y_sum. Add try block in your statistics function.
def statistic(name, index, mode):
try:
y_sum = 0
for i in range(5):
try:
y_sum += y_values[i].get()
except:
pass
y_normalized = y_sum / 5
mean.set(y_normalized)
except tk.TclError:
pass
For my coursework i am making a booking system and i have been messing around trying to make a page which shows current week lessons and when the button is clicked it comes up with that students details on a separate page.But i don't know how to go about passing that time into my open page sub(which writes a txt file which is going to be used for SQL to get the students details). The current way i have done it just passes the max times into the sub.
from tkinter import *
import datetime
class Application(Frame):
def __init__(self, master):
""" Initialize the frame. """
super(Application, self).__init__(master)
self.grid()
self.timetable_button_gen_weekdays()
self.timetable_button_gen_weekends()
def timetable_button_gen_weekdays(self):
c = datetime.datetime(100,1,1,16,00,00)
self.Monday_lbl = Label(self, text = "Monday")
self.Monday_lbl.grid(row = 1, column = 0)
self.Tuesday_lbl = Label(self, text = "Tuesday")
self.Tuesday_lbl.grid(row = 2, column = 0)
self.Wednesday_lbl = Label(self, text = "Wednesday")
self.Wednesday_lbl.grid(row = 3, column = 0)
self.Thursday_lbl = Label(self, text = "Thursday")
self.Thursday_lbl.grid(row = 4, column = 0)
self.Friday_lbl = Label(self, text = "Friday")
self.Friday_lbl.grid(row = 5, column = 0)
for k in range(8):
b = c + datetime.timedelta(minutes = (30 * k))
d = b + datetime.timedelta(minutes = (30))
self.i_time_weekdays_lbl = Label(self, text = b.time().strftime('%H:%M')+" to "+d.time().strftime('%H:%M'))
self.i_time_weekdays_lbl.grid(row = 0, column = k + 1)
for i in range(5):
for a in range(8):
b = c + datetime.timedelta(minutes = (30 * a))
d = b + datetime.timedelta(minutes = (30))
bttn_i_a = Button(self, text = "available",command = lambda: self.OpenPage(b.time().strftime('%H:%M'),d.time().strftime('%H:%M')))
bttn_i_a.grid(row = i + 1, column = a + 1)
bttn_i_a.config(height = 2, width = 10)
def timetable_button_gen_weekends(self):
c = datetime.datetime(100,1,1,10,00,00)
self.Saturday_lbl = Label(self, text = "Saturday")
self.Saturday_lbl.grid(row = 8, column = 0)
self.Sunday_lbl = Label(self, text = "Sunday")
self.Sunday_lbl.grid(row = 9, column = 0)
self.weekend_lbl = Label(self, text = "Weekend")
self.weekend_lbl.grid(row = 6, column = 1, sticky = W)
for k in range(10):
b = c + datetime.timedelta(minutes = (30 * k))
d = b + datetime.timedelta(minutes = (30))
self.i_time_weekdays_lbl = Label(self, text = b.time().strftime('%H:%M')+" to "+d.time().strftime('%H:%M'))
self.i_time_weekdays_lbl.grid(row = 7, column = k + 1)
for i in range(2):
for a in range(10):
b = c + datetime.timedelta(minutes = (30 * a))
d = b + datetime.timedelta(minutes = (30))
bttn_i_a = Button(self, text = "available",command = lambda: self.OpenPage(b.time().strftime('%H:%M'),d.time().strftime('%H:%M')))
bttn_i_a.grid(row = i + 8, column = a + 1)
bttn_i_a.config(height = 2, width = 10)
def OpenPage(self,startime,finishtime):
file = open("PassTimes.txt","w")
file.write(startime)
file.write("\n")
file.write(finishtime)
print(startime)
print(finishtime)
filepath = "PresentStudent.py"
global_namespace = {"__file__": filepath, "__name__": "__main__"}
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), global_namespace)
root = Tk()
root.title("test")
root.geometry("2000x2000")
app = Application(root)
root.mainloop()
Welcome to SO.
General
IMHO, running the main routine of "PresentStudent.py" does not look that clean.
It works, but a main routine is built for when the script is called directly, not when it is imported and used in some other script.
Are you aware of the modules functionality in python?
I would recommend creating a function in PresentStudent.py that does what you are doing inside your main routine. Give the function parameters to pass the .txt-Filename.
e.g.
def presentStudentCall(inputFile):
and use it inside your script like:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# here we import PresentStudent.py, as we import it __main__ will not run
import PresentStudent
#[...]
def OpenPage(self, stime, etime):
#[...]
# Instead of executing a file we call the function from the module
PresentStudent.presentStudentCall(file)
If you want to display the data inside a second frame, you could also declare a class in PresentStudent.py and use it like:
def OpenPage(self, stime, etime):
#[...]
student=PresentStudent.Student() # assuming to name the class "Student"
student.presentStudentCall(file)
Your question itself
using the lambda does not need to be the best way. In matters of scope and garbage collecting your code only passes the last generated "b"s and "c"s to the definition.
What you could do to make it work is calculating the sender item in OpenPage:
To achieve that, I recommend having arrays for your time spans storing starting times.
Like
c = datetime.datetime(100,1,1,16,00,00)
self.weektimes = ["%s"%(c+datetime.timedelta(minutes=30*k)) for k in range(8)]
self.weekendtimes = ["%s"%((c+datetime.timedelta(minutes=30*k)) for k in range(10)]
First you need to bind the click event to the widget(in that case your button)
bttn_i_a.bind("<Button-1>", self.OnPage)
Your OpenPage could then look like this:
def OpenPage(self, event):
import time
# With that, we get the row and column where we clicked in
grid_info=event.widget.grid_info()
# week or weekend?
if grid_info["row"] > 5: #may depend on amount of headers
_timearray=self.weekendtimes
else:
_timearray=self.weektimes
# get the column
col=grid_info["column"]
# get the startTime
stime=_timearray[col]
# end time is +30 minutes
etime="%s"%(time.strptime("%s"%stime, "%H:%M")+time.struct_time(tm_min=30))
# now call the handler...
I am making a chatroom. In my code, I open a login window, and a user window. Then I choose the username from a listbox and then click Start Chat in classMainScreen
In my temporarily attempt, after click that button, it should create a child window with a tithe with username. That is, if I choose "A" "B" and "C" in the listbox2, it should open three windows with titles "A" "B" and "C"
However, I don't want to open two window with the same title. If I choose a username which has already used in the window title, it should just pull that window to the front.
I know there is a function can just check if a child window exists. But it can't detect the title of windows. These windows have the same instance(Do I describe it right?) but different titles in the function ChatScreen. So what should I do?
My code doesn't work exactly what I describe because I just make the temporarily code. I just want to know how to detect if the window is open by detecting the title first, then I can change my code.
Thanks for any help!
from Tkinter import *
import socket
########HelperFunction########
def chunkstring (block): #Use to make the block into chunks and count the sum of ASCII value of chunks
M = []
for i in range(0, 512, 32):
L = str((block[0 + i : 32 + i]))
sum = 0
for r in range(len(L)):
sum = sum + ord(L[r])
M.append(sum)
return M
def leftrotate(x, c):
return (x << c) & 0xFFFFFFFF | (x >> (32 - c) & 0x7FFFFFFF >> (32 - c))
########Connection########
def StartConnection (IPAddress, PortNumber): #Use to set up the connection between computers and servers
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IPAddress, PortNumber))
return s
def login (s, username, password): #Login Function
print username
print password
s.send('LOGIN ' + username + '\n')
data = s.recv(512)
List = data.split(" ") #send the commend and get something back
CH = List[2] # pick up the CHALLENGE code
CH = CH[:-2] # delete the last two unnecessary code
PD = password
message = PD + CH # combine password and CHALLENGE together
block = message + "1"
block = block + "0" * (512 - len(message) - 3 - 1) # add '0' to block and remain the space for last three digits
numLen = len(str(len(message)))
if numLen == 2: #If the password is very long, we should consider the last digits may be affected
block = block + "0" + str(len(message))
elif numLen == 3:
block = block + str(len(message))
M = chunkstring(block)
########## MD5
P = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
K = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391]
#Initialize variables
a0 = 0x67452301
b0 = 0xefcdab89
c0 = 0x98badcfe
d0 = 0x10325476
A = a0
B = b0
C = c0
D = d0
#Mainloop
for i in range(0, 64):
if i >= 0 and i <= 15:
F = (B & C) | ((~ B) & D)
F = F & 0xFFFFFFFF
g = i
elif i >= 16 and i <= 31:
F = (D & B) | ((~ D) & C)
F = F & 0xFFFFFFFF
g = (5 * i + 1) % 16
elif i >= 32 and i <= 47:
F = B ^ C ^ D
F = F & 0xFFFFFFFF
g = (3 * i + 5) % 16
elif i >= 48 and i <= 63:
F = C ^ (B | (~ D))
F = F & 0xFFFFFFFF
g = (7 * i) % 16
dTemp = D
D = C
C = B
B = B + leftrotate((A + F + K[i] + M[g]), P[i])
B = B & 0xFFFFFFFF
A = dTemp
#Add this chunk's hash to result so far:
a0 = (a0 + A) & 0xFFFFFFFF
b0 = (b0 + B) & 0xFFFFFFFF
c0 = (c0 + C) & 0xFFFFFFFF
d0 = (d0 + D) & 0xFFFFFFFF
result = str(a0) + str(b0) + str(c0) + str(d0)
s.send("LOGIN " + username + " " + result + "\n") #send messagedigest to server
reply = s.recv(512)
print reply
if "Successful" in reply:
openMainScreen()
return True
else:
First.quit()
return False
def getUsers(s):
s.send('#users')
data = s.recv(512)
data = data.split('#') # use "#" help to split the list
data = data[4:] # start from the 4th element in order to avoid the elements I don't need
return data
def getFriends(s):
s.send('#friends')
data = s.recv(512)
data = data.split('#')
data = data[4:]
return data
def getRequests(s):
s.send('#rxrqst')
data = s.recv(512)
data = data.split('#')
data = data[3:]
return data
def sendFriendRequest(s, friend):
num = len(str(friend)) # count the len of my friends' name
if 22 + num < 100: # if it is short, so I can add three 0s
size = '000' + str(22 + num)
elif 22 + num >= 100: # if it is long, I have to consider another situation
size = '00' + str(22 + num)
s.send('#' + size + '#request#friend#' + friend)
data = s.recv(512)
if "#ok" in data:
SendRequestDialog()
return True
else:
print False
return False
def acceptFriendRequest(s, friend):
num = len(str(friend)) # count the len of my friends' name
if 21 + num < 100: # if it is short, so I can add three 0s
size = '000' + str(21 + num)
elif 21 + num >= 100: # if it is long, I have to consider another situation
size = '00' + str(21 + num)
s.send('#' + size + '#accept#friend#' + friend)
data = s.recv(512)
if "#ok" in data:
Second.update()
return True
else:
return False
########Interface#########
#--------Login--------#
class Login(Frame):
def __init__(self, master):
frame = Frame(master)
frame.pack()
First.geometry("250x250")
self.lab1 = Label(frame, text = "Username")
self.lab1.grid(row = 0, column = 125)
self.ent1 = Entry(frame)
self.ent1.grid(row = 1, column = 125)
self.lab2 = Label(frame, text = "Password")
self.lab2.grid(row = 2, column = 125)
self.ent2 = Entry(frame, show = "*")
self.ent2.grid(row = 3, column = 125)
self.button = Button(frame, text = "OK", command = self.Submit)
self.button.grid(row = 5, column = 125)
def Submit(self):
username = self.ent1.get()
password = self.ent2.get()
login(ss, username, password)
class MainScreen(Frame):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.lab1 = Label(frame, text = "All Users")
self.lab1.grid(row = 1, column = 100)
self.lab2 = Label(frame, text = "Your Friends")
self.lab2.grid(row = 1, column = 300)
self.lab3 = Label(frame, text = "Pending Requests")
self.lab3.grid(row = 1, column = 500)
self.button1 = Button(frame, text = "Send Request", command = self.SendRequest)
self.button1.grid(row = 3, column = 100)
self.button2 = Button(frame, text = "Start Chat", command = ChatScreen)
self.button2.grid(row = 3, column = 300)
self.button3 = Button(frame, text = "Accept Request", command = self.AcceptRequest)
self.button3.grid(row = 3, column = 500)
users = getUsers(ss)
self.listbox1 = Listbox(frame)
self.listbox1.grid(row = 2, column = 100)
for item in users:
self.listbox1.insert(END, item)
self.value1 = str((self.listbox1.get(ACTIVE)))
friends = getFriends(ss)
self.listbox2 = Listbox(frame)
self.listbox2.grid(row = 2, column = 300)
for item in friends:
self.listbox2.insert(END, item)
requests = getRequests(ss)
self.listbox3 = Listbox(frame)
self.listbox3.grid(row = 2, column = 500)
for item in requests:
self.listbox3.insert(END, item)
def SendRequest(self):
friends = self.value1
sendFriendRequest(ss, friends)
def AcceptRequest(self):
Accept = str((self.listbox3.get(ACTIVE)))
num = self.listbox3.curselection()
num = int(num[0])
if acceptFriendRequest(ss, Accept) == True:
self.listbox2.insert(END, Accept)
self.listbox3.delete(num)
def StartChat(self):
global chatguy
chatguy = str((self.listbox2.get(ACTIVE)))
def ChatScreen():
aaa = Toplevel(First)
aaa.title("aaa1")
aaa.geometry("300x200")
def SendRequestDialog():
Third = Toplevel(First)
Third.title("Send Successfully")
Third.geometry("300x100")
lab = Label(Third, text = "The friend request was successfully sent")
lab.pack()
def openMainScreen():
global Second
Second = Toplevel(First)
Second.title("Chat with Client")
Second.geometry("600x400")
mainscreen = MainScreen(Second)
First = Tk()
First.title("Login")
LoginScreen = Login(First)
ss = StartConnection("86.36.34.215", 15112)
First.mainloop()
Since First is the parent of all your windows in the widget tree, you can check the children of First to detect already open windows. Something like this:
for key,val in First.children.iteritems():
if isinstance(val, tk.Toplevel):
print("window: " + val.title())
#or to get a list of all titles
titles = map(lambda win:win.title() , filter(lambda w : isinstance(w, tk.Toplevel), First.children.itervalues()))
if title not in titles:
#...