Tkinter variable value is not passed to other class - python

I have a little bit of strange problem and I will try to explain.
So I am trying to connect to WiFi through tkinter, and I am passing variables like name of the WiFi and the password, between classes, and its working. I know this because I am displaying them in Labels, but when I try to connect to WiFi, the variables are not passed as arguments to the connection string.
Here is part of my code :
import tkinter as tk
from PIL import Image, ImageTk
import time
import os
from wifi import Cell, Scheme
LARGE_FONT = ("Verdana", 12)
from tkinter import END
class SeaofBTCapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
self.geometry("480x800")
self.label = tk.Label(text="This is the start page",background="blue",height=2)
self.label.pack(side="top", fill="x", pady=0)
self.time1 = ''
self.time2 = time.strftime('%H:%M:%S')
self.watch = tk.Label(self, text=self.time2, font=('times', 12, 'bold'))
self.watch.pack()
self.changeLabel() #first call it manually
self.a=tk.StringVar()
self.passcode=tk.StringVar()
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=100)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (SetUpPage,ChoseWIFI,TypePassword,Connecting):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(SetUpPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
def changeLabel(self):
self.time2 = time.strftime('%H:%M:%S')
self.watch.configure(text=self.time2)
self.after(200, self.changeLabel) # it'll call itself continuously
class SetUpPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
image = Image.open("wifi_icon.gif")
image = image.resize((50, 50), Image.ANTIALIAS)
self.reset_img = ImageTk.PhotoImage(image)
image1 = Image.open("ethernet_icon.gif")
image1 = image1.resize((50, 50), Image.ANTIALIAS)
self.reset_img1 = ImageTk.PhotoImage(image1)
self.but = tk.Button(self, text="WORK IN", height=180, width=180, image=self.reset_img,command=lambda: controller.show_frame(ChoseWIFI)).place(x=150, y=125)
self.but1 = tk.Button(self, text="WORK OUT", height=180, width=180, image=self.reset_img1).place(x=150, y=425)
class ChoseWIFI(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller=controller
self.mylistbox=tk.Listbox(self,width=80,height=10,font=('times',13))
self.mylistbox.bind('<<ListboxSelect>>',self.CurSelet)
self.mylistbox.place(x=100,y=190)
self.wifiscan()
self.but = tk.Button(self, text="CONNECT", height=10, width=10,command=lambda: controller.show_frame(TypePassword)).place(x=150, y=525)
def wifiscan(self):
allSSID = [cell.ssid for cell in Cell.all('wlan0')]
print (allSSID )# prints all available WIFI SSIDs
for i in range(len(allSSID )):
if print(str(allSSID [i]))== print(myssid):
a = i
print("hit")
myssidA = allSSID [a]
print( myssidA )
break
else:
print ("getout")
print (myssid)
self.itemsforlistbox=allSSID
for items in self.itemsforlistbox:
self.mylistbox.insert(END,items)
def CurSelet(self,a):
value=self.mylistbox.get(self.mylistbox.curselection())
self.o=self.controller.a
self.o.set(value)
class TypePassword(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller=controller
#self.entry1 = tk.Label(self, textvariable=self.controller.shared_data["username"])
#self.entry1.pack()
self.L2 = tk.Label(self, textvariable=self.controller.a)
self.L2.pack()
self.L1 = tk.Label(self, text="Type password")
self.L1.pack()
self.E1 = tk.Entry(self, bd=5)
self.E1.place(x=150, y=325)
#self.connect()
self.but = tk.Button(self, text="CONNECT", height=10, width=10,command=lambda:[self.connect(), controller.show_frame(Connecting)]).place(x=150, y=525)
def connect(self):
self.controller.passcode.set(self.E1.get())
#os.system('nmcli d wifi connect "%s" password %s iface %s' % (self.controller.a,self.controller.passcode, self.controller.a)) # vive1234 is the password to my wifi myssidA is the wifi name
self.pas=self.controller.passcode
self.passw = self.E1.get()
self.pas.set(self.passw)
class Connecting(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller=controller
self.entry1 = tk.Label(self, text="CONNECTING.....")
self.entry1.pack()
self.entry2 = tk.Label(self, textvariable=self.controller.a)
self.entry2.pack()
self.entry3 = tk.Label(self, textvariable=self.controller.passcode)
self.entry3.pack()
self.but = tk.Button(self, text="CONNECT11", height=10, width=10,command=self.k).place(x=150, y=525)
#self.but.tk.bind(('<but>', self.k))
def k(self):
#connection string for WIFI
os.system('nmcli d wifi connect "%s" password %s iface %s' % (self.controller.a,self.controller.passcode, self.controller.a)) # vi
print("KKKK")
if __name__ == "__main__":
# Calls its attribute.
app = SeaofBTCapp()
a=app.changeLabel()
app.after(200,a )
# Calls its attribute.
app.mainloop()

Related

Tkinter adding Images issue

so I have looked about but cant find anything that works for me so if I add a image to my first page (log in page) the image will display fine. However if I try and add it to my main page I get the error pyimage 1
Here is the code: (I've tried to remove all the code not needed to shorten it)
import tkinter as tk
from tkinter import ttk
from tkinter import Scrollbar, messagebox
import os
from PIL import ImageTk,Image
global appcwd
appcwd = os.getcwd()
class Login_Start(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
main_frame = tk.Frame(self, bg="black", height=768, width=1366)
main_frame.pack(fill="both", expand="true")
self.geometry("1366x768")
#INSERTING IMAGE HERE
#path = "{}\\grem.png".format(appcwd)
#img = ImageTk.PhotoImage(Image.open(path))
#pic2lab = tk.Label(main_frame, image=img)
#pic2lab.photo = img
#pic2lab.pack()
loginbut = tk.Button(main_frame, width=10, text='Login', command=lambda: Get_Login())
loginbut.pack()
def Get_Login():
validation = True
if validation:
root.deiconify()
top.destroy()
else:
tk.messagebox.showerror("Information", "The details are either wrong or you need to register")
class MenuBar(tk.Menu):
def __init__(self, parent):
tk.Menu.__init__(self, parent)
menu_file = tk.Menu(self, tearoff=0)
self.add_cascade(label="File", menu=menu_file)
menu_file.add_command(label="Main Menu", command=lambda: parent.show_frame(Main_Page))
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
main_frame = tk.Frame(self, bg="grey", height=768, width=1366)
main_frame.pack_propagate(0)
main_frame.pack(fill="both", expand="true")
main_frame.grid_rowconfigure(0, weight=1)
main_frame.grid_columnconfigure(0, weight=1)
self.geometry("1366x768")
self.frames = {}
pages = (Main_Page, Admin_Page)
for F in pages:
frame = F(main_frame, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(Main_Page)
menubar = MenuBar(self)
tk.Tk.config(self, menu=menubar)
def show_frame(self, name):
frame = self.frames[name]
frame.tkraise()
class Temp(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.main_frame = tk.Frame(self, bg="black", height=768, width=1366)
self.main_frame.pack_propagate(0)
self.main_frame.pack(fill="both", expand="true")
self.main_frame.grid_rowconfigure(0, weight=1)
self.main_frame.grid_columnconfigure(0, weight=1)
self.main = tk.LabelFrame(self.main_frame, bg='black')
self.main.place(relx=0.01, rely=0.21, height=490, width=1330)
class Main_Page(Temp):
def __init__(self, parent, controller):
Temp.__init__(self, parent)
mainlabel = tk.Label(self.main, font=("Trebuchet MS Bold", 16), bg="grey", fg="black", text="TEXT")
mainlabel.pack()
path = "{}\\grem.png".format(appcwd)
img = ImageTk.PhotoImage(Image.open(path))
pic2lab = tk.Label(self.main, image=img)
pic2lab.photo = img
pic2lab.pack()
butbut = tk.Button(self.main, text="press", command=lambda:controller.show_frame(Admin_Page))
butbut.pack()
class Admin_Page(Temp):
def __init__(self, parent, controller):
Temp.__init__(self, parent)
hm = tk.Label(self.main, bg="grey", fg='black', text='Admin_Page')
hm.place(rely=0.02, relx=0.01,)
top = Login_Start()
top.title("main title")
root = App()
root.withdraw()
root.title("main title")
root.mainloop()
Like I said works fine in the Login_Start() Class but won't in the Main_Page()

Updating or "Refreshing" frames in Tkinter

This basically creates all the frames and brings the one we call to the front right?
So as some variables change i want the frames to change accordingly, i tried a few refreshing functions i found while searching in google but none of them worked in this code.
oooooooooooooooooooooooooooooo
Code:
import tkinter as tk
from tkinter import *
from tkinter import ttk
from functools import partial
class MovieTicketapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.geometry(self, "500x400")
container = tk.Frame(self)
container.pack(side='top', fill='both', expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
global user
self.frames = {}
for F in (StartPage, SignUp, Login, EditMovie):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky='nsew')
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
global user
button_signup = ttk.Button(self, text='Sign Up',
command=lambda: controller.show_frame(SignUp)).pack(pady=10, padx=15)
button_EditMovie = ttk.Button(self, text='Edit Movie Details',
command=lambda: controller.show_frame(EditMovie))
if user == "admin":
button_EditMovie.pack(pady=10, padx=15)
class SignUp(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
button_login = ttk.Button(self, text='Login',
command=lambda: controller.show_frame(Login)).pack(pady=10, padx=15)
button_home = tk.Button(self, text='Home',
command=lambda: StartPage.__init__()).pack(pady=10, padx=15)
class Login(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
def validateLogin(email, password):
e = email.get()
p = password.get()
global user
user = e
StartPage.update(self)
controller.show_frame(StartPage)
self.pack_forget()
emailLabel = tk.Label(self, text='Email').pack()
email = tk.StringVar()
emailEntry = tk.Entry(self, textvariable = email).pack()
passwordLabel = tk.Label(self,text="Password").pack()
password = tk.StringVar()
passwordEntry = tk.Entry(self, textvariable=password, show='*').pack()
validateLogin = partial(validateLogin, email, password)
loginButton = tk.Button(self, text="Login", command= validateLogin).pack(pady=15, padx=15)
button_home = tk.Button(self, text='Home',
command=lambda: controller.show_frame(StartPage)).pack(pady=10, padx=15)
class EditMovie(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
button_home = tk.Button(self, text='Home',
command=lambda: controller.show_frame(StartPage))
button_home.pack(pady=10, padx=10)
app = MovieTicketapp()
app.mainloop()
......

having issues with the if statement

With the if-statement that I have put in, it would only display the lose statement even if it is correct.
I'm not sure if the way I wrote the statement is correct.
I'm trying to make it that when pressing start both labels would show a number between 1 to 21.
Also, if it's possible, I want to make it that when the hit button is pressed, a number would be added to the label. For example, pressing hit would add 10 + 5, then display the total.
LOCATED IN CLASS TTY:
import tkinter as tk
k = 10
Q = 10
J = 10
A = 11 or 1
class WINDOW(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Memory") #sets the window title
container = tk.Frame(self)#Name of frame to refer to
container.pack(side="top", fill="both", expand=True)#size of window
container.grid_rowconfigure(0, weight=4)#size of window
container.grid_columnconfigure(0, weight=4)
self.frames = {}
for F in (MainMenu, tty):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("MainMenu")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
class MainMenu(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(background = 'white')
label = tk.Label(self, text="Memory",font=(15),
borderwidth=5, relief="solid")
label.pack(side="top", fill="y", pady=15, padx=270)
label.pack(fill="both")
button1 = tk.Button(self, text="Start", relief="solid",
borderwidth=5,width=30,
font=(17),command=lambda:
controller.show_frame("tty"))
button1.pack()
button3 = tk.Button(self,
text="Quit",relief="solid",borderwidth=4,width=30,font=(17),command = quit)
button3.place(x="420", y ="50")
button3.pack()
class tty(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(background = "white")
def win():
if score > deal:
tts = tk.Label(self, text="win", font=(20))
tts.pack()
else:
lose = tk.Label(self, text="lose", font=(10))
lose.pack() #The if statement
deal = tk.Label(self, text="18", font=(18))
deal.pack(side="top", fill="y", pady=15, padx=270)
score = tk.Label(self, text="19", font=(18))
score.pack()
f = tk.Frame(self)
button1 = tk.Button(f,borderwidth=5, text="stand", font=(18),command =
lambda: win())#This is the button that i want to display the label
button1.grid(row=0,column=0)
button2 = tk.Button(f, text="Hit",borderwidth=5, font=(18))
button2.grid(row=0,column=1)
f.pack(side="bottom")
button3 = tk.Button(self, text="Quit", font=(18))
button3.pack(side="right", pady=50)
if __name__ == "__main__":
app = WINDOW()
app.geometry("800x400")
app.mainloop()
if score > deal: is comparing two tkinter label objects rather than the value of score and deal. Try getting the value of the labels and converting them to integers before doing the comparision.
if int(score['text']) > int(deal['text']):
To help with your other questions.
To chose a random number between 1 and 21, use the randint function contained inside python's random module (see code below). I've added a new randomise function which will be called after the page is created to randomly select a value for deal and score.
With the hit button, i've added a new function hit which will take the current score, and add another random value to it.
import tkinter as tk
from random import randint
k = 10
Q = 10
J = 10
A = 11 or 1
class WINDOW(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Memory") #sets the window title
container = tk.Frame(self)#Name of frame to refer to
container.pack(side="top", fill="both", expand=True)#size of window
container.grid_rowconfigure(0, weight=4)#size of window
container.grid_columnconfigure(0, weight=4)
self.frames = {}
for F in (MainMenu, tty):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("MainMenu")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
class MainMenu(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(background = 'white')
label = tk.Label(self, text="Memory",font=(15),
borderwidth=5, relief="solid")
label.pack(side="top", fill="y", pady=15, padx=270)
label.pack(fill="both")
button1 = tk.Button(self, text="Start", relief="solid",
borderwidth=5,width=30,
font=(17),command=lambda:
controller.show_frame("tty"))
button1.pack()
button3 = tk.Button(self,
text="Quit",relief="solid",borderwidth=4,width=30,font=(17),command = quit)
button3.place(x="420", y ="50")
button3.pack()
class tty(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(background = "white")
self.deal = tk.Label(self, text="18", font=(18))
self.deal.pack(side="top", fill="y", pady=15, padx=270)
self.score = tk.Label(self, text="19", font=(18))
self.score.pack()
f = tk.Frame(self)
button1 = tk.Button(f,borderwidth=5, text="stand", font=(18),command = self.win)#This is the button that i want to display the label
button1.grid(row=0,column=0)
button2 = tk.Button(f, text="Hit",borderwidth=5, font=(18),command = self.hit)
button2.grid(row=0,column=1)
f.pack(side="bottom")
button3 = tk.Button(self, text="Quit", font=(18))
button3.pack(side="right", pady=50)
self.randomise()
def randomise(self):
self.deal['text'] = str(randint(1,21))
self.score['text'] = str(randint(1,21))
def hit(self):
current_score = int(self.score['text'])
new_score = current_score + randint(1,21)
self.score['text'] = str(new_score)
def win(self):
if int(self.score['text']) > int(self.deal['text']):
tts = tk.Label(self, text="win", font=(20))
tts.pack()
else:
lose = tk.Label(self, text="lose", font=(10))
lose.pack() #The if statement
if __name__ == "__main__":
app = WINDOW()
app.geometry("800x400")
app.mainloop()

the tkinter widgets in my classes are not displaying

I'm trying to write a code that contains multiple pages and can be switched to when a button is clicked on. it worked initially but my widgets are not displaying, and there is neither a warning or an error message. Secondly, what is the difference between using tk and tk.TK?
from tkinter import *
import tkinter as tk
class moreTab(tk.Tk):
def __init__(self):
Tk.__init__(self)
self.geometry("1200x600")
container = Frame(self, bg='#c9e3c1')
container.pack(side = "top", fill = 'both', expand = True)
container.grid_rowconfigure(0, weight = 1)
container.grid_columnconfigure(0, weight = 1)
self.frames = {}
for q in (pageone, widget):
frame = q(container,self)
self.frames[q] = frame
frame.place(x= 0,y = 0)
self.raise_frame(pageone)
def raise_frame(self,cont):
frame = self.frames[cont]
frame.tkraise()
class widget(Frame):
def __init__(self, master, control):
Frame.__init__(self, master)
lab = tk.Label(self, text="main page")
lab.place(x = 10, y = 40)
but = tk.Button(self, text='visit start page', command=lambda:
control.raise_frame(pageone))
but.place(x = 10, y = 70)
class pageone(Frame):
def __init__(self, master, control):
Frame.__init__(self,master)
lab = Label(self, text = 'welcome to Game Analysis')
lab.place(x = 10, y = 10)
but = Button(self, text = "Start", command = lambda:
control.raise_frame(widget))
but.place(x = 10, y = 20)
app = moreTab()
app.mainloop()
It turns the issue was that you were using place(). Use the grid geometry manager. Using both import tkinter as tk and from tkinter import * is meaningless. Use one and be consistent. If you use the latter, you have everything available, hence you will write, say Button(...). But if you use the former, you will have to refer each widget like tk.Button(...).
import tkinter as tk
class moreTab(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.geometry("1200x600")
container = tk.Frame(self, bg='#c9e3c1')
container.pack(side = "top", fill = 'both', expand = True)
container.grid_rowconfigure(0, weight = 1)
container.grid_columnconfigure(0, weight = 1)
self.frames = {}
for q in (pageone, widget):
frame = q(container, self)
self.frames[q] = frame
frame.grid(row=0, column=0, sticky='nsew')
self.raise_frame(pageone)
def raise_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class widget(tk.Frame):
def __init__(self, master, control):
tk.Frame.__init__(self, master)
lab = tk.Label(self, text="main page")
lab.grid(row=0, column=0, padx=10, pady=10)
but = tk.Button(self, text='visit start page', command=lambda: control.raise_frame(pageone))
but.grid(row=1, column=0, padx=10, pady=10)
class pageone(tk.Frame):
def __init__(self, master, control):
tk.Frame.__init__(self, master)
lab = tk.Label(self, text = 'welcome to Game Analysis')
lab.grid(row=0, column=0, padx=10, pady=10)
but = tk.Button(self, text = "Start", command = lambda: control.raise_frame(widget))
but.grid(row=1, column=0, padx=10, pady=10)
app = moreTab()
app.mainloop()

Why are my widgets not showing up on the 3rd screen

When you select 2 duelist on the second screen the program shows a 3rd screen that should display 2 labels and 2 entry widgets for the user to enter the names of the players. But I can't seem to figure out why the widgets are not showing up. The section of code that involves this issue is the the block for the class TwoPlayer. Thank you!
import tkinter as tk
largeFont = ("Veranda", 18)
field1 = 'Duelist 1', 'Duelist 2'
names = []
class Yugioh_backEnd(tk.Tk):
#set default initializion
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "YuGiOh Duel Calculator")
#containers
container = tk.Frame(self)
#set pack method for container
container.pack(side="top", fill="both", expand=True)
#set grid method for container
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
#selects which frame to show
self.frames = {}
for F in (StartPage, NumPlayers, TwoPlayer):
frame = F(container, self)
self.frames[F]=frame
frame.grid(row=0, column=0, sticky="nsew")
#show Frame
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#greet the user
greeting = tk.Label(self, text = "Welcome to\n YuGiOh Duel Calculator!", font = largeFont)
greeting.pack(pady=(10,40),padx=30)
#Enter the next window
lets_duel = tk.Button(self, text="Lets Duel!!!", command=lambda: controller.show_frame(NumPlayers))
lets_duel.pack(pady=(0,30),padx=30)
class NumPlayers(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#prompt for players quantity
prompt1 = tk.Label(self, text = "How many duelist?", font = largeFont)
prompt1.pack(pady=(10,40),padx=30)
#Number of players
twoPlayers = tk.Button(self, text = "2 Duelists", command=lambda: controller.show_frame(TwoPlayer))
return1 = tk.Button(self, text="Return Home", command=lambda: controller.show_frame(StartPage))
#Add buttons to frame
return1.pack(pady=(0,30),padx=30)
twoPlayers.pack(pady=(0,10),padx=30)
#Two player mode
class TwoPlayer(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
def makeform(field1):
for field in field1:
row = tk.Frame()
lab = tk.Label(row, width=15, text=field, anchor='w')
ent = tk.Entry(row)
row.pack(side="top", padx=5, pady=5)
lab.pack(side="left")
ent.pack(side="right")
names.append((field, ent))
return names
if __name__ == ("__init__"):
ents = makeform(field1)
b1 = tk.Button(text='Show',
command=lambda: controller.show_frame(StartPage))
b1.pack(padx=5, pady=5)
app = Yugioh_backEnd()
app.mainloop()

Categories

Resources