I'm able to move data from one class frame to another, unfortunately, I can't update the text in the new frame. I can only pack the new data below the original pack
class LabelApp(tk.Frame):
def __init__(self, master, xy_motion=[-1,-1]):
tk.Frame.__init__(self, master )
self.pack()
print('LapApp: ' + str(xy_motion[0]))
self.master = master
self.xy_motion=xy_motion
self.xlabel = tk.Label(text=self.xy_motion[0])
self.xlabel.pack()
def update_label(self, xy_motion ):
self.xlabel.config(text=xy_motion[0])
the print statement above shows correct data
code that is passing over data
class VideoDisplayApp(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack()
self.master = master
self.image_label = tk.Label(master=self.master) # label for the vide.
..
.
.
def motion(self, event):
x, y = event.x, event.y
self.xy_motion = [x,y]
print('{}, {}'.format(x, y))
self.motion=tk.Frame(self.master)
self.app = LabelApp(self.motion, self.xy_motion )
Main window
class MainWindow(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack(padx=15, pady=15)
self.master.title("Mob")
self.master.resizable(False, False)
self.master.tk_setPalette(background='#e6e6e6')
frame_video = tk.Frame(self)
frame_video.grid(row=0, column=0)
# frame_video.geometry("200x200")
VideoDisplayApp(frame_video)
#
frame_bottom = tk.Frame(self)
frame_bottom.grid(row=1, column=0)
LabelApp(frame_bottom)
#
frame_left = tk.Frame(self)
frame_left.grid(row=0, column=1)
ClickOnFrame(frame_left)
Related
In my gui I want to import data from a file, display it in a listbox, do a computation, show the result in a listbox and then export the data as a csv.
I have been able to do most of the GUI but the interaction between classes makes no sense to me, here is my code:
class MainApplication(tk.Tk):
def __init__(self, master, *args, **kwargs):
self.master = master
self.container = tk.Frame(self)
self.container.pack(side="top", fill="both", expand=True)
self.container.grid_rowconfigure(0, weight=1)
self.container.grid_columnconfigure(0, weight=1)
self.frames = {}
self.frames["computation"] = computation(master=self.container, controller=self)
self.frames["openFile"] = openFile(master=self.container, controller=self)
...
def get_page(self, c):
return self.frames[c]
class computation(tk.Frame):
def __init__(self, master, controller):
tk.Frame.__init__(self, master)
self.master = master
self.controller = controller
self.listbox = Listbox(self.master)
self.listbox.pack()
def add_listbox_item(self):
for i in df.columns:
self.listbox.insert(END,i)
class openFile(tk.Frame):
def __init__(self, master, controller):
tk.Frame.__init__(self, master)
self.master = master
self.controller = controller
self.openfile = Button(self.master, command=self.import_df)
def import_df(self):
self.filename = filedialog.askopenfilename(...)
global df
df = pd.read_csv(self.filename)
computation = self.controller.get_page("computation")
computation.add_listbox_item()
Everything seems to be executing, even a print statement in add_listbox_item but the listbox just wont be filled with the data it's being fed, any ideas?
Communication between objects
The idea is create a Toplevel window from Gui and after Toplevel closed send the data (name) from Toplevel Entry back to Gui
How object app can know whether the toplev object was destroyed?
or with other words
How can object of Gui know that the object of My_Toplevel is closed?
from tkinter import *
font1 = font=("Open Sans Standard",16,"bold")
class My_Toplevel():
def __init__(self, master=None):
self.master = master
self.toplev = Toplevel(master)
self.name = None
self.create_widgets()
def create_widgets(self):
self.entry_name = Entry(self.toplev, font=font1)
self.button_ok = Button(self.toplev, text="Ok", font=font1,
command=self.get_name)
self.entry_name.pack()
self.button_ok.pack()
def get_name(self):
self.name = self.entry_name.get()
self.toplev.destroy()
class Gui(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.pack()
self.master = master
self.label_text = Label(self, text="Foo Bar Window", font=font1)
self.label_text.pack()
self.button_toplevel = Button(self, text="Create Toplevel",
command=self.get_toplevel, font=font1)
self.button_toplevel.pack()
def get_toplevel(self):
self.my_top = My_Toplevel(self)
if __name__ == "__main__":
root = Tk()
root.title("Parent")
app = Gui(root)
root.mainloop()
You need to pass the data to the Gui instance before you destroy My_Toplevel. One way to do that is to save the name string as an attribute of the Gui instance since you pass that the master parameter when you call My_Toplevel. For example:
from tkinter import *
font1 = font=("Open Sans Standard",16,"bold")
class My_Toplevel():
def __init__(self, master=None):
self.master = master
self.toplev = Toplevel(master)
self.create_widgets()
def create_widgets(self):
self.entry_name = Entry(self.toplev, font=font1)
self.button_ok = Button(self.toplev, text="Ok", font=font1,
command=self.get_name)
self.entry_name.pack()
self.button_ok.pack()
def get_name(self):
self.master.name_data = self.entry_name.get()
self.toplev.destroy()
class Gui(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.pack()
self.master = master
self.label_text = Label(self, text="Foo Bar Window", font=font1)
self.label_text.pack()
self.button_toplevel = Button(self, text="Create Toplevel",
command=self.get_toplevel, font=font1)
self.button_toplevel.pack()
self.name_data = None
Button(self, text="show name", command=self.show_name).pack()
def show_name(self):
print("Name =", self.name_data)
def get_toplevel(self):
self.my_top = My_Toplevel(self)
if __name__ == "__main__":
root = Tk()
root.title("Parent")
app = Gui(root)
root.mainloop()
Press the "show name" button to print the name string to the console.
If you need to save more than a single string, you could append the name to a list, save it in a dictionary, etc.
If you like, you can call the Gui.show_name method just before the TopLevel window is destroyed:
def get_name(self):
self.master.name_data = self.entry_name.get()
self.master.show_name()
self.toplev.destroy()
I am making a game with levels and in each level, I will need to be using different operators and/or different ranges. My problem is that I don't know how to change the variables in a function from a different class. I would like to do this so I don't need to copy and paste my code making it lengthy. I'd like to use self.Answer and self.strQuestion for mulitple scope.
The code below is just to make the classes functional.
from tkinter import *
import tkinter as tk
import random
from Tkinter import messagebox
class BattleMaths(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, levelone, leveltwo):
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)
lvl1_button = Button(self, text="LEVEL 1", command=lambda: controller.show_frame(levelone))
lvl1_button.place(relx=0.5, rely=0.5, anchor='center')
I want to put the questions def into class leveltwo while changing it to self.Answer = int(numOne) * int(numTwo) and self.strQuestion = "{} x {}".format(str(numOne), str(numTwo))
class levelone(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
def widgets(self):
#widgets here
def question(self):
self.UserAnswer = ''
numOne = random.randrange(1,10)
numTwo = random.randrange(1,10)
self.Answer = int(numOne) + int(numTwo) #change this
self.strQuestion = "{} + {}".format(str(numOne), str(numTwo)) #and change this
def answer(self):
#answer checker
class leveltwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#question def here
root = BattleMaths()
root.title("Battle Maths")
root.geometry("400x250")
root.resizable(0,0)
root.mainloop()
Create the variables you want in the main class (BattleMaths), then you can alter them in the child classes via controller.my_variable.
Example: self.Answer created in BattleMaths and accessed in levelone via controller.Answer
I would like to delete an object from another class and make it invisible.
For example a class with a button called Button 1.
Another class with a button called Button 2.
When I click on Button 2 I don't want to see Button 1.
from tkinter import*
class Menu(Frame):
def __init__(self,master):
Frame.__init__(self,master,bg = "white")
self.grid()
self.button_clicks = 0
self.create_widgets()
def create_widgets(self):
self.button = Button(self)
self.button["text"] = "Button 1: 0"
self.button["command"] = self.update_count
self.button.grid(ipadx = 5, padx = 150)
def update_count(self):
self.button["text"] = "Another try: " + str(self.button_clicks)
self.button_clicks += 1
if self.button_clicks > 10:
self.button_clicks = 0
class noMenu(Frame):
def __init__(self,master):
Frame.__init__(self,master,bg = "white")
self.grid()
self.button_clicks = 0
self.create_widgets()
def create_widgets(self):
self.button = Button(self)
self.button["text"] = "Bye button 1"
self.button["command"] = self.byeMenu
self.button.grid(ipadx = 5, padx = 150)
def byeMenu(self):
Menu.grid_forget()
app = Tk()
app.configure(background= "white")
app.title("Button on my but")
app.geometry("400x200")
first = Menu(app)
second = noMenu(app)
app.mainloop()
If you want widgets to interact use the fact that they have common ancestry to achieve this. Then if you want a widget to "disappear" you can do so with the geometry manger you are using
An example to work from might be:
import Tkinter
class Main(Tkinter.Tk):
def __init__(self, parent):
Tkinter.Tk.__init__(self, parent)
self.first = Menu(self)
self.second = noMenu(self)
def first_button_response(self):
self.first.button.pack_forget()
class noMenu(Tkinter.Frame):
def __init__(self, parent):
Tkinter.Frame.__init__(self, parent)
self.button = Tkinter.Button(
self, text="Bye button 1", command=parent.first_button_response
)
self.button.pack()
self.pack()
class Menu(Tkinter.Frame):
def __init__(self, parent):
Tkinter.Frame.__init__(self, parent)
self.button = Tkinter.Button(self, text="Button 1")
self.button.pack()
self.pack()
if __name__ == "__main__":
app = Main(None)
app.mainloop()
Here I used pack_forget to remove the first button. If you want to use the grid manager you should look into grid_remove or grid_forget depending on whether you want to at some point have the button reappear or not.
I'm trying to create a simple UI with Tkinter and I have run into a problem. My code looks like this:
class UIController(tk.Tk):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
self.frames = {}
for F in (StartPage, BrowsePage, StudentPage):
frame = F(self, container)
self.frames[F] = frame
frame.title("StudyApp")
self.showFrame(StartPage)
self.centerWindow()
def showFrame(self, c):
frame = self.frames[c]
frame.tkraise()
def centerWindow(self):
w = 300
h = 350
sw = self.master.winfo_screenwidth()
sh = self.master.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2
self.master.geometry('%dx%d+%d+%d' % (w, h, x, y))
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack()
self.L1 = Label(self, text="Search by credits:")
self.L1.place(x=18, y=45)
self.startYear = Entry(self, bd=2)
self.startYear.place(x=20, y=70)
self.startYear.bind("<Return>", View.enter(startYear.get()))
self.quitButton = Button(self, text="Quit", command=sys.exit)
self.quitButton.pack(side="bottom", padx=5, pady=5, fill=X)
self.searchButton = Button(self, text="Search")
self.searchButton.pack(side="bottom", padx=5, pady=0, fill=X)
class BrowsePage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
class StudentPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
root = tk.Tk()
root.resizable(width=False, height=False)
uicontrol = UIController(root)
root.mainloop()
It gives a TypeError that the constructor takes 2 arguments but 3 were given. What I'm trying to do is have the 3 pages (StartPage, BrowsePage and StudentPage) in the frame 'container', and bring them up as needed with button pushes and such. I don't understand why I'm getting this error.
EDIT:
Added the UIController call.
EDIT2:
Added the page classes StartPage, BrowsePage and StudentPage. The latter two classes are only husks at this point.
I think this is the line that is causing the issue, you cannot pass the self instance to the constructor.
frame = F(self, container)
Can you please check and add more information to the question to understand what you are trying to achieve.
You can just add in __init__ one more argument, controller.
This works for me:
def __init__(self, master, controller):
tk.Frame.__init__(self, master)