Related
I've been trying to call the class that is in my mainloop, but whenever I properly call it makes it that the program doesn't even launch anymore. I've been attempting to call it in order to get a method, which would return the current frame. I am aware that my code uses controller and parent to communicate between classes, but I haven't managed to fully grasp an understanding of these. If I call the mainlooped class, with "test = Database_project()", then the program won't run anymore. Can someone explain this to me? I'm trying to get the scrollbar feature to work on specific frames, and I haven't managed to figure out just yet. I'm trying to call the mainlooped class in the "CreatePage" class. Thank you in advance!
from tkinter import *
import tkinter as tk
class Database_Project(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
stack_frame_container = tk.Frame(self)
stack_frame_container.grid_columnconfigure(0, weight=1)
stack_frame_container.grid_rowconfigure(0, weight=1)
stack_frame_container.pack(side="top", fill="both", expand=True)
self.frameslist = {}
for frame in (MainPage, CreatePage):
frame_occurrence = frame.__name__
active_frame = frame(parent=stack_frame_container, controller=self)
self.frameslist[frame_occurrence] = active_frame
active_frame.grid(row=0, column=0, sticky="snew")
#self.frameslist["CreatePage"].dbproject = self.frameslist["Datanase_Project"]
self.current_frame("MainPage")
print(self.frameslist)
def current_frame(self, frame_occurrence):
active_frame = self.frameslist[frame_occurrence]
active_frame.tkraise()
def get_current_frame(self, frame_occurrence):
active_frame = self.frameslist[frame_occurrence]
return active_frame
class MainPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label_create = tk.Label(self, text="Create and insert data").grid(row=0, column=0, padx=50, pady=(50,0))
create_button = tk.Button(self, text="CREATE", command=lambda: controller.current_frame("CreatePage")).grid(row=1, column=0)
label_read = tk.Label(self, text="Query over data").grid(row=0, column=1, padx=50, pady=(50,0))
read_button = tk.Button(self, text="READ").grid(row=1, column=1)
label_update = tk.Label(self, text="Modify existing data").grid(row=2, column=0, padx=50, pady=(50,0))
update_button = tk.Button(self, text="UPDATE").grid(row=3, column=0, pady=(0,50))
label_delete = tk.Label(self, text="Remove data").grid(row=2, column=1, padx=50, pady=(50,0))
delete_button = tk.Button(self, text="DELETE").grid(row=3, column=1, pady=(0,50))
class CreatePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.inputlist = []
self.newinputlist = []
Test = Database_Project()
#active_frame = Test.get_current_frame("CreatePage")
#scrollbar = tk.Scrollbar(active_frame, orient="vertical")
#scrollbar.grid(row=0, column=2, stick="ns", columnspan=10)
#text["yscrollcommand"] =
labels = [tk.Label(self, text="Enter unique field"), tk.Label(self, text="Enter corresponding the value/s")]
self.inputlist.append(labels[:])
for toplabels in range(1):
self.inputlist[toplabels][0].grid(row=toplabels, column=0, padx=10, pady=5)
self.inputlist[toplabels][1].grid(row=toplabels, column=1, padx=10, pady=5)
first_entries = [tk.Entry(self, borderwidth=5), tk.Text(self, borderwidth=5, height= 5, width=20)]
self.newinputlist.append(first_entries[:])
self.inputlist.append(first_entries[:])
for x in range(0, len(self.newinputlist) + 1):
self.newinputlist[0][x].grid(row=1, column=x, padx=10, pady=5)
button_input_1 = [tk.Button(self, text="ADD FIELD/VALUE", command=self.add_insert), tk.Button(self, text="BACK", command=lambda: controller.current_frame("MainPage"))]
self.inputlist.append(button_input_1[:])
button_input_2 = [tk.Button(self, text="IMPORT FILE"), tk.Button(self, text="SUBMIT DATA", command=self.submit_data)]
self.inputlist.append(button_input_2[:])
for button in range(len(self.inputlist) - 2, len(self.inputlist)):
self.inputlist[button][0].grid(row=button, column=0, padx=10, pady=5)
self.inputlist[button][1].grid(row=button, column=1, padx=10, pady=5)
def add_insert(self):
add_input = [tk.Entry(self, borderwidth=5), tk.Text(self, borderwidth=5, height= 5, width=20)]
self.inputlist.insert(-2, add_input)
self.newinputlist.append(add_input)
for widget in self.children.values():
widget.grid_forget()
for index, widgets in enumerate(self.inputlist):
print(widgets)
widget_one = widgets[0]
widget_two = widgets[1]
print(str(index), widget_one, widget_two)
widget_one.grid(row=index, column=0, padx=10, pady=5)
widget_two.grid(row=index, column=1, padx=10)
def submit_data(self):
for index, entries in enumerate(self.newinputlist):
my_label = Label(self, text=str(entries[0].get()) + str(entries[1].get("1.0", END)))
my_label.grid(row=len(self.inputlist) + index, column=0)
if __name__ == "__main__":
NoSQL_Project = Database_Project()
NoSQL_Project.title("NoSQL Database Project")
NoSQL_Project.maxsize(500, 500)
NoSQL_Project.mainloop()
The entry value is just simply doesn't get passed into the function, whatever I do.
class Registration(tk.Frame):
def __init__(self, parent, controller):
name_var = tk.StringVar()
name_entry = ttk.Entry(self, textvariable=name_var)
name_entry.grid(row=1, column=1)
button1 = ttk.Button(self, text="Registration", command=self.RegFunction(name_var.get()))
button1.grid(row=4, column=4)
def RegFunction(self, name)
print(name)
Edit:
I just realized, if I add a variable to the function, it gets called as soon as I run the program, and it doesn't care about the button; but if I don't give it a variable, it works as it should, only when I push the button.
Here is the whole code
import tkinter as tk
from tkinter import ttk
class ToDoList(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 (LogIn, Registration):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(LogIn)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class LogIn(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
# label of frame Layout 2
label = ttk.Label(self, text="Log In")
label.grid(row=0, column=4, padx=10, pady=10)
username_label = ttk.Label(self, text="Username :")
username_label.grid(row=1, column=1)
password_label = ttk.Label(self, text="Password:")
password_label.grid(row=2, column=1)
usrname_entry = ttk.Entry(self)
usrname_entry.grid(row=1, column=2)
password_entry = ttk.Entry(self)
password_entry.grid(row=2, column=2)
button2 = ttk.Button(self, text="Registration",
command=lambda: controller.show_frame(Registration))
button2.grid(row=4, column=1, padx=10, pady=10)
class Registration(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = ttk.Label(self, text="Registration")
label.grid(row=0, column=4, padx=10, pady=10)
name_label = ttk.Label(self, text="Username:")
name_label.grid(row=1, column=0)
pass1_label = ttk.Label(self, text="Password:")
pass1_label.grid(row=2, column=0)
pass2_label = ttk.Label(self, text="Password again:")
pass2_label.grid(row=3, column=0)
name_var = tk.StringVar()
name_entry = ttk.Entry(self, textvariable=name_var)
name_entry.grid(row=1, column=1)
pass1_entry = ttk.Entry(self)
pass1_entry.grid(row=2, column=1)
pass2_entry = ttk.Entry(self)
pass2_entry.grid(row=3, column=1)
k = 12
button1 = ttk.Button(self, text="Registration", command=self.RegFunction(k))
button1.grid(row=4, column=4, padx=10, pady=10)
button2 = ttk.Button(self, text="Back to Login",
command=lambda: controller.show_frame(LogIn))
button2.grid(row=4, column=0, padx=10, pady=10)
def RegFunction(self, x):
print("Something", x)
app = ToDoList()
app.mainloop()
There's a difference between calling a function and passing in a function's name so it can be called later on. The ttk.Button command= expects a function name (or reference) to be passed in, so that the named or referenced function can be called later. You are calling the function rather than passing in its name, so things go awry.
Change:
button1 = ttk.Button(self, text="Registration", command=self.RegFunction(name_var.get()))
to:
button1 = ttk.Button(self, text="Registration", command=lambda: self.RegFunction(name_var.get()))
and you'll be closer to your goal. The lambda tells Python not to call the function but rather just return a reference to it that can be used to call it later.
Once you do that, you'll see that you have a typo in your function definition -- you're missing a colon at the end of the def statement. So, change:
def RegFunction(self, name)
to:
def RegFunction(self, name): # colon added at end
command=self.RegFunction(name_var.get()) will execute self.RegFunction() immediately. You need to use lambda:
class Registration(tk.Frame):
def __init__(self, parent, controller):
super().__init__(parent)
name_var = tk.StringVar()
name_entry = ttk.Entry(self, textvariable=name_var)
name_entry.grid(row=1, column=1)
button1 = ttk.Button(self, text="Registration", command=lambda: self.RegFunction(name_var.get()))
button1.grid(row=4, column=4)
def RegFunction(self, name):
print(name)
Note that your code did not call super().__init__(parent) inside __init__().
You are not calling the entry function, but the outcome of the function. Try it without the brackets:
button1 = ttk.Button(self, text="Registration", command=self.RegFunction(name_var))
Also, the RegFunction misses the colon:
def RegFunction(self, name):
print(name)
I was trying to program a kind of calculator in Python using the Tkinter library. My problem is that I watch some pages that says that the way to set de heidth and weidth of a button is using rowconfigure and columnconfigure. The problem is that when I run the script it doesn't work. I don't know what I'm doing bad so pls help me
Here is the code
import tkinter as tk
def insert_number(variable, entry):
result = variable + entry
return result
conjunt = ""
class MainWindow(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.grid()
self.config(bg="blue")
self.button1 = tk.Button(text="1", command=insert_number(conjunt, "1")).grid(
column=0, row=0)
self.button1 = tk.Button(text="2", command=insert_number(conjunt, "2")).grid(
column=1, row=0)
self.button1 = tk.Button(text="3", command=insert_number(conjunt, "3")).grid(
column=2, row=0)
self.button1 = tk.Button(text="4", command=insert_number(conjunt, "1")).grid(
column=0, row=1)
self.button1 = tk.Button(text="5", command=insert_number(conjunt, "1")).grid(
column=1, row=1)
self.button1 = tk.Button(text="6", command=insert_number(conjunt, "1")).grid(
column=2, row=1)
self.button1 = tk.Button(text="7", command=insert_number(conjunt, "1")).grid(
column=0, row=2)
self.button1 = tk.Button(text="8", command=insert_number(conjunt, "1")).grid(
column=1, row=2)
self.button1 = tk.Button(text="9", command=insert_number(conjunt, "1")).grid(
column=2, row=2)
self.button1 = tk.Button(text="0", command=insert_number(conjunt, "1")).grid(
column=1, row=3)
self.columnconfigure(0, weight=1)
self.columnconfigure(1, weight=1)
self.rowconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
def give_result(self):
pass
def main():
root = tk.Tk()
root.title("Calculadora")
buttons_frame = MainWindow(root)
buttons_frame.grid()
root.mainloop()
if __name__ == "__main__":
main()
I'm working on a small GUI to query information from our CMDB to display for users. The trouble I am having is after an event in one class occurs(button), I want to update a combobox in another class. I thought I should use tk.StringVar() to pass the list, but the combobox only shows a 'PC_VAR#' value and doesn't update. Could anyone offer any assistance please?
#!/usr/bin/python
import Tkinter as tk
import ttk
import signal
class LoginUI:
def __init__(self, frame):
self.frame = frame
# Set default list entry
self.dc_list = tk.StringVar()
self.dc_list.set(['Login first'])
# Add a button to log in
self.button = tk.Button(self.frame, text='Login', command=self.change_combobox)
self.button.grid(column=0, row=0, pady=5)
def change_combobox(self):
# Change combobox values
dc_list = ['Site_1', 'Site_2', 'Site_3']
self.dc_list.set(dc_list)
class QueryUI:
def __init__(self, frame, dc_list):
self.frame = frame
self.dc = tk.StringVar()
self.dc_list = tk.StringVar()
self.dc_list.set(dc_list)
# Create site combobox
tk.Label(self.frame, text='Site:').grid(column=0, row=0, sticky="w")
self.dc_combobox = ttk.Combobox(
self.frame,
textvariable=self.dc,
width=20,
state='readonly'
)
self.dc_combobox['values'] = self.dc_list.get()
self.dc_combobox.grid(column=1, row=0, sticky="w")
class App:
def __init__(self, root):
self.root = root
self.root.title('Logging Handler')
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
# Create the left frame panels
left_frame = tk.Frame(self.root, padx=5, pady=5)
login_frame = tk.LabelFrame(left_frame, text="Login", borderwidth=2, relief="groove", padx=5, pady=5)
query_frame = tk.LabelFrame(left_frame, text="Query", borderwidth=2, relief="groove", padx=5, pady=5)
# Align frames
left_frame.grid(row=0, column=0, sticky="nw")
login_frame.grid(row=0, column=0, pady=5, sticky="nw")
query_frame.grid(row=1, column=0, pady=5, sticky="nw")
# Initialize all frames
self.login = LoginUI(login_frame)
self.query = QueryUI(query_frame, self.login.dc_list)
self.root.protocol('WM_DELETE_WINDOW', self.quit)
self.root.bind('<Control-q>', self.quit)
signal.signal(signal.SIGINT, self.quit)
def quit(self, *args):
self.root.destroy()
def main():
root = tk.Tk()
app = App(root)
app.root.mainloop()
if __name__ == '__main__':
main()
What I would do here is pass the controlling class (app) to the class needed to update the combobox. This way we can interact with it later if need be. By passing self of App to LoginUI we can then interact with the class attributes and methods of App from within LoginUI. This makes it a simple matter to update the combobox.
That said you really don't Need all the StringVars. Just past the list as a list and you will be good to go.
import Tkinter as tk
import ttk
import signal
class LoginUI:
def __init__(self, controller, frame):
self.controller = controller
self.frame = frame
self.dc_list = ['Login first']
self.button = tk.Button(self.frame, text='Login', command=self.change_combobox)
self.button.grid(column=0, row=0, pady=5)
def change_combobox(self):
self.controller.query.dc_combobox['values'] = ['Site_1', 'Site_2', 'Site_3']
self.controller.query.dc.set('Site_1')
class QueryUI:
def __init__(self, frame, dc_list):
self.frame = frame
self.dc = tk.StringVar()
tk.Label(self.frame, text='Site:').grid(column=0, row=0, sticky="w")
self.dc_combobox = ttk.Combobox(self.frame, textvariable=self.dc, width=20, state='readonly')
self.dc_combobox['values'] = dc_list
self.dc_combobox.grid(column=1, row=0, sticky="w")
class App:
def __init__(self, root):
self.root = root
self.root.title('Logging Handler')
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
left_frame = tk.Frame(self.root, padx=5, pady=5)
login_frame = tk.LabelFrame(left_frame, text="Login", borderwidth=2, relief="groove", padx=5, pady=5)
query_frame = tk.LabelFrame(left_frame, text="Query", borderwidth=2, relief="groove", padx=5, pady=5)
left_frame.grid(row=0, column=0, sticky="nw")
login_frame.grid(row=0, column=0, pady=5, sticky="nw")
query_frame.grid(row=1, column=0, pady=5, sticky="nw")
self.login = LoginUI(self, login_frame)
self.query = QueryUI(query_frame, self.login.dc_list)
self.root.protocol('WM_DELETE_WINDOW', self.quit)
self.root.bind('<Control-q>', self.quit)
signal.signal(signal.SIGINT, self.quit)
def quit(self, *args):
self.root.destroy()
if __name__ == '__main__':
root = tk.Tk()
app = App(root)
app.root.mainloop()
I'm new im Python, just started to learn about class and tkinter, so forgive me "messy" code.
I'm trying to enter some string to field nr1, and after click a button, print this string in console and store this value for later:
from tkinter import Tk, BOTH, RIGHT, RAISED, BOTTOM, TOP, X, StringVar
from tkinter.ttk import Frame, Button, Entry
class AD(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, v=None, raw_input=None)
self.parent = parent
self.parent.geometry("250x150+300+300")
self.parent.title("Trolollo")
self.parent.resizable(False, False)
self.inp = None
self.v = StringVar()
self.raw_input = None
self.initUI()
def user_input(self):
global inp
a = self.raw_input(self.v.get())
inp = a
return inp
def initUI(self):
self.pack(fill=BOTH, expand=True)
frame = Frame(self, relief=RAISED, borderwidth=0)
frame.pack(fill=BOTH, expand=True)
self.entry1 = Entry(frame, textvariable=self.v)
self.entry1.pack(side=TOP, fill=X, expand=False, padx=2, pady=2)
self.entry1.focus_set()
rename_button = Button(frame, text="Dispaly text", command = self.user_input())
rename_button.pack(side=TOP, expand=False, padx=2, pady=2)
entry2 = Entry(frame)
entry2.pack(side=TOP, fill=X, expand=False, padx=2, pady=2)
quit_button = Button(self, text="Quit", command=self.quit)
quit_button.pack(side=RIGHT, padx=5, pady=5)
ok_button = Button(self, text="OK")
ok_button.pack(side=RIGHT, padx=5, pady=5)
def main():
root = Tk()
app = AD(root)
root.mainloop()
if __name__ == '__main__':
main()
After executing code, i get:
TypeError: 'NoneType' object is not callable
Any help would me appreciated
ISSUES:
First issue laid in your rename_button's option "command=self.user_input()". You were suppose to name the function
and not execute the function. Putting the () symbol meant you
executed the function when your code loaded, i.e. it executed once
w/o pressing the rename button.
Second issue was the erroneous code in your function user_input. This caused your error msg.
ANSWER: Code with the suggested corrections.
from tkinter import *
from tkinter.ttk import *
class AD(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, v=None, raw_input=None)
self.parent = parent
self.parent.geometry("250x150+300+300")
self.parent.title("Trolollo")
self.parent.resizable(False, False)
self.inp = None
self.v = StringVar()
self.raw_input = None
self.initUI()
def user_input(self):
# Get entry1 value, store it as an attribute and print to console
self.raw_input = self.v.get()
print(self.raw_input)
def initUI(self):
self.frame = Frame(self, relief=RAISED, borderwidth=0)
self.frame.pack(fill=BOTH, expand=True)
self.entry1 = Entry(self.frame, textvariable=self.v)
self.entry1.pack(side=TOP, fill=X, expand=False, padx=2, pady=2)
self.entry1.focus_set()
#self.rename_button = Button(self.frame, text="Dispaly text",
# command = self.user_input())
self.rename_button = Button(self.frame, text="Display text",
command = self.user_input)
self.rename_button.pack(side=TOP, expand=False, padx=2, pady=2)
# You can remove the triple quotes to display these widgets
"""
self.entry2 = Entry(self.frame)
self.entry2.pack(side=TOP, fill=X, expand=False, padx=2, pady=2)
self.quit_button = Button(self.frame, text="Quit", command=self.quit)
self.quit_button.pack(side=RIGHT, padx=5, pady=5)
self.ok_button = Button(self.frame, text="OK")
self.ok_button.pack(side=RIGHT, padx=5, pady=5)
"""
self.pack(fill=BOTH, expand=True)
def main():
root = Tk()
app = AD(root)
root.mainloop()
Your GUI :
SUGGESTIONS:
Do remember to put self. in front of your widgets.
Do test one widget at a time to help you debug your code.