I have made two separate GUI screens, one as login.py and user_intern.py and in user_intern.py I have a button called login_button, so when I click login the login.py which contains GUI for login screen should execute and the user_intern.py should close automatically and I didn't used class (OOP) here, I have written code fully with functions only so hereby I attached the codes and screenshots of screens.
User_intern.py
user_intern.py_pic
from tkinter import *
from tkinter import ttk
from PIL import Image,ImageTk
import os
import pickle
import mysql.connector as sql
from tkinter import messagebox
def login1():
host = host_entry.get()
port = port_entry.get()
username = username_entry.get()
password = password_entry.get()
database="cars"
spec=sql.connect(host=host,user=username,password=password,port=port)
if spec.is_connected():
messagebox.showinfo("Connected","Database connected Sucessfully")
else:
messagebox.showerror("Exists", "Database is already connected")
spec.close()
root = Tk()
root.geometry("1067x600")
root.configure(background="black")
root.resizable(False, False)
root.title("School Diaries")
#background image
bg = ImageTk.PhotoImage(file="files\Sublime Light1.jpg")
lbl_bg = Label(root,image=bg)
lbl_bg.place(x=0,y=0,relwidth=1,relheight=1)
#Labels
host_label = Label(root, text="Host Name ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 12, "bold"))
host_label.place(x=675, y=115)
host_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#host_entry.insert(0, "localhost")
host_entry.place(x=687, y=139, width=145)
port_label = Label(root, text="Port ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
port_label.place(x=675, y=190)
port_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#port_entry.insert(0, "3307")
port_entry.place(x=690, y=213, width=145)
username_label = Label(root, text="Username ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
username_label.place(x=675, y=265)
username_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#username_entry.insert(0, "root")
username_entry.place(x=687, y=287, width=145)
password_label = Label(root, text="Password ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
password_label.place(x=675, y=338)
password_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#password_entry.insert(0, "root")
password_entry.place(x=687, y=361, width=145)
#buttons
submit = ImageTk.PhotoImage(file='Pics\submit.png')
submit_button = Button(root, image=submit,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white",borderwidth=0, background="white", cursor="hand2",command=login1)
submit_button.place(x=655, y=440)
login = ImageTk.PhotoImage(file='Pics\login.png')
login_button = Button(root, image=login,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white",borderwidth=0, background="white", cursor="hand2")
login_button.place(x=785, y=442)
root.mainloop()
login.py
login.py_pic
from tkinter import *
from tkinter import ttk
from PIL import Image,ImageTk
import os
import pickle
import mysql.connector as sql
from tkinter import messagebox
def login():
#host = user_inter.host_entry.get()
#port = user_inter.port_entry.get()
username = username_entry.get()
password = password_entry.get()
spec=sql.connect(host=host,user=username,password=password,port=port)
if spec.is_connected():
messagebox.showinfo("Connected","Database connected Sucessfully")
else:
messagebox.showerror("Exists", "Failed")
mycur=spec.cursor()
mycur.execute()
root = Tk()
root.geometry("1067x600")
root.configure(background="black")
root.resizable(False, False)
root.title("School Diaries")
#background
bg = ImageTk.PhotoImage(file="files\login.jpg")
lbl_bg = Label(root,image=bg)
lbl_bg.place(x=0,y=0,relwidth=1,relheight=1)
#Labels
login_lbl = Label(root, text="Login", bg="white", fg="#4f4e4d",font=("San Francisco", 45))
login_lbl.place(x=757,y=120)
username_label = Label(root, text="Username ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
username_label.place(x=675, y=190)
username_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#username_entry.insert(0, "root")
username_entry.place(x=695, y=215, width=190)
password_label = Label(root, text="Password ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
password_label.place(x=675, y=280)
password_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#password_entry.insert(0, "root")
password_entry.place(x=692, y=305, width=190)
login = ImageTk.PhotoImage(file='Pics\login.png')
login_button = Button(root, image=login,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white",borderwidth=0, background="white", cursor="hand2")
login_button.place(x=770, y=390)
root.mainloop()
You can do any edits in code to get the output.
Related
I'm new to tkinter gui framework of python
I have a doubt in treeview widget of the tkinter gui
my doubt is how to resize the treeview widget so that i can place the two treeview widget aside photos attached below and i doing a project on mysql database so for the frontend i used tkinter gui
Screenshot of output
from tkinter import *
from tkinter import ttk
from PIL import Image,ImageTk
import os
import pickle
import mysql.connector as sql
from tkinter import messagebox
def click_home():
"""set to default home tab where details like no. of students, employees, department shows """
home_frame = Frame(root)
home_frame.place(x=120, y=105, height=440, width=910)
home_dashboard_fram_r=Image.open('files\home_new.png')
home_dashboard_fram_r=home_dashboard_fram_r.resize((910,440),Image.ANTIALIAS)
home_dashboard_frame = ImageTk.PhotoImage(home_dashboard_fram_r)
home_panel = Label(home_frame, image=home_dashboard_frame, bg="white")
home_panel.image= home_dashboard_frame
home_panel.pack(fill='both', expand='yes')
def click_manage():
""" opens new frame from where one can go to manage students, employees, departments, course, section
and batch"""
manage_frame = Frame(root, bg="white")
manage_frame.place(x=120, y=105, height=440, width=910)
manage_dashboard_frame_r = Image.open('files\\manage_frame1.png')
manage_dashboard_frame_r=manage_dashboard_frame_r.resize((910,440),Image.ANTIALIAS)
manage_dashboard_frame = ImageTk.PhotoImage(manage_dashboard_frame_r)
manage_panel = Label(manage_frame, image=manage_dashboard_frame, bg="white")
manage_panel.image = manage_dashboard_frame
manage_panel.pack(fill='both', expand='yes')
student_r=Image.open('Pics\\student.png')
student_r=student_r.resize((100,100),Image.ANTIALIAS)
student = ImageTk.PhotoImage(student_r)
student_button = Button(manage_frame, image=student, relief=FLAT, borderwidth=0,activebackground="white", bg="white", cursor="hand2")
student_button.image = student
student_button.place(x=120, y=115)
employee_r=Image.open('Pics\\employee.png')
employee_r=employee_r.resize((100,100),Image.ANTIALIAS)
employee = ImageTk.PhotoImage(employee_r)
employee_button = Button(manage_frame, image=employee, relief=FLAT, borderwidth=0,activebackground="white", bg="white", cursor="hand2")
employee_button.image =employee
employee_button.place(x=395, y=115)
department_r=Image.open('Pics\\department.png')
department_r=department_r.resize((100,100),Image.ANTIALIAS)
department = ImageTk.PhotoImage(department_r)
department_button = Button(manage_frame, image=department, relief=FLAT, borderwidth=0,activebackground="white", bg="white", cursor="hand2")
department_button.image = department
department_button.place(x=672, y=115)
course_r=Image.open('Pics\\course.png')
course_r=course_r.resize((100,100),Image.ANTIALIAS)
course = ImageTk.PhotoImage(course_r)
course_button = Button(manage_frame, image=course, relief=FLAT, borderwidth=0,activebackground="white", bg="white", cursor="hand2")
course_button.image = course
course_button.place(x=121, y=300)
section_r=Image.open('Pics\\section.png')
section_r=section_r.resize((100,100),Image.ANTIALIAS)
section = ImageTk.PhotoImage(section_r)
section_button = Button(manage_frame, image=section, relief=FLAT, borderwidth=0,activebackground="white", bg="white", cursor="hand2")
section_button.image = section
section_button.place(x=396, y=300)
batch_r=Image.open('Pics\\batch.png')
batch_r=batch_r.resize((100,100),Image.ANTIALIAS)
batch = ImageTk.PhotoImage(batch_r)
batch_button = Button(manage_frame, image=batch, relief=FLAT, borderwidth=0,activebackground="white", bg="white", cursor="hand2")
batch_button.image = batch
batch_button.place(x=673, y=300)
def click_view():
""" Displays partial data into tree view of students, employees, departments, courses when clicked view tab
on interface """
view_frame = Frame(root, bg="white")
view_frame.place(x=120, y=105, height=440, width=910)
view_dashboard_frame_r=Image.open('Pics\\view_frame.png')
view_dashboard_frame_r=view_dashboard_frame_r.resize((910,440),Image.ANTIALIAS)
view_dashboard_frame = ImageTk.PhotoImage(view_dashboard_frame_r)
view_panel = Label(view_frame, image=view_dashboard_frame, bg="white")
view_panel.image=view_dashboard_frame
view_panel.pack(fill='both', expand='yes')
department_view_label = Label(view_frame, text="View Department Information ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
department_view_label.place(x=770, y=290)
course_view_label = Label(view_frame, text="View Course Information ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
course_view_label.place(x=170, y=290)
# ========================================================================
# ============================Displaying Student Information==============
# ========================================================================
student_view_label = Label(view_frame, text="View Students Information ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
student_view_label.place(x=170, y=6)
view_student_frame = Frame(view_frame, bg="white")
view_student_frame.place(x=10, y=40, height=250, width=575)
style = ttk.Style()
style.configure("Treeview.Heading", font=('yu gothic ui', 10, "bold"), foreground="red")
style.configure("Treeview", font=('yu gothic ui', 9, "bold"), foreground="#f29b0f")
scroll_y = Scrollbar(view_student_frame, orient=VERTICAL)
scroll_x = Scrollbar(view_student_frame, orient=HORIZONTAL)
view_student_tree = ttk.Treeview(view_student_frame,columns=("STUDENT ID", "STUDENT NAME", "COURSE ENROLLED", "PHONE NO."),xscrollcommand=scroll_x.set, yscrollcommand=scroll_y.set,height=2)
scroll_x.pack(side=BOTTOM, fill=X)
scroll_y.pack(side=RIGHT, fill=Y)
scroll_x.config(command=view_student_tree.xview)
scroll_y.config(command=view_student_tree.yview)
# ==========================TreeView Heading====================
view_student_tree.heading("STUDENT ID", text="STUDENT ID")
view_student_tree.heading("STUDENT NAME", text="STUDENT NAME")
view_student_tree.heading("COURSE ENROLLED", text="COURSE ENROLLED")
view_student_tree.heading("PHONE NO.", text="PHONE NO.")
view_student_tree["show"] = "headings"
# ==========================TreeView Column====================
view_student_tree.column("STUDENT ID", width=50)
view_student_tree.column("STUDENT NAME", width=50)
view_student_tree.column("COURSE ENROLLED", width=50)
view_student_tree.column("PHONE NO.", width=50)
view_student_tree.pack(fill=BOTH, expand=1)
# ========================================================================
# =========================Displaying instructor Information==============
# ========================================================================
view_employee_frame = Frame(view_frame, bg="white")
view_employee_frame.place(x=595, y=40, height=250, width=575)
employee_view_label = Label(view_frame, text="View Employees Information ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
employee_view_label.place(x=600, y=5)
scroll_y_e = Scrollbar(view_employee_frame, orient=VERTICAL)
scroll_x_e = Scrollbar(view_employee_frame, orient=HORIZONTAL)
view_employee_tree = ttk.Treeview(view_employee_frame,columns=("EMPLOYEE ID", "EMPLOYEE NAME", "DEPARTMENT", "EMPLOYEE TYPE"),xscrollcommand=scroll_x_e.set, yscrollcommand=scroll_y_e.set)
scroll_x_e.pack(side=BOTTOM, fill=X)
scroll_y_e.pack(side=RIGHT, fill=Y)
scroll_x_e.config(command=view_employee_tree.xview)
scroll_y_e.config(command=view_employee_tree.yview)
# ==========================TreeView Heading====================
view_employee_tree.heading("EMPLOYEE ID", text="EMPLOYEE ID")
view_employee_tree.heading("EMPLOYEE NAME", text="EMPLOYEE NAME")
view_employee_tree.heading("DEPARTMENT", text="DEPARTMENT")
view_employee_tree.heading("EMPLOYEE TYPE", text="EMPLOYEE TYPE")
view_employee_tree["show"] = "headings"
# ==========================TreeView Column====================
view_employee_tree.column("EMPLOYEE ID", width=50)
view_employee_tree.column("EMPLOYEE NAME", width=150)
view_employee_tree.column("DEPARTMENT", width=100)
view_employee_tree.column("EMPLOYEE TYPE", width=100)
view_employee_tree.pack(fill=BOTH, expand=1)
root = Tk()
root.geometry("1067x600")
root.title("Dashboard")
root.resizable(False, False)
#root.iconbitmap('images\\logo.ico')
bg = ImageTk.PhotoImage(file="files\Dashboard1.jpg")
lbl_bg = Label(root,image=bg)
lbl_bg.place(x=0,y=0,relwidth=1,relheight=1)
home_r=Image.open('Pics\\home.png')
home_r=home_r.resize((50, 50), Image.ANTIALIAS)
home = ImageTk.PhotoImage(home_r)
home_button = Button(root, image=home,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white", borderwidth=0, background="white", cursor="hand2",command=click_home)
home_button.place(x=40, y=113)
manage_r=Image.open('Pics\\manage.png')
manage_r=manage_r.resize((50, 50), Image.ANTIALIAS)
manage = ImageTk.PhotoImage(manage_r)
manage_button = Button(root, image=manage,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white", borderwidth=0, background="white", cursor="hand2",command=click_manage)
manage_button.place(x=38, y=205)
view_r=Image.open('Pics\\view.png')
view_r=view_r.resize((50, 50), Image.ANTIALIAS)
view = ImageTk.PhotoImage(view_r)
view_button = Button(root, image=view,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white", borderwidth=0, background="white", cursor="hand2",command=click_view)
view_button.place(x=36, y=299)
setting_r = Image.open('Pics\\setting.png')
setting_r=setting_r.resize((50, 50), Image.ANTIALIAS)
setting = ImageTk.PhotoImage(setting_r)
setting_button = Button(root, image=setting,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white", borderwidth=0, background="white", cursor="hand2")
setting_button.place(x=38, y=395)
exit_1_r=Image.open('Pics\\exit_button.png')
exit_1_r=exit_1_r.resize((50, 50), Image.ANTIALIAS)
exit_1 = ImageTk.PhotoImage(exit_1_r)
exit_button = Button(root, image=exit_1,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white", borderwidth=0, background="white", cursor="hand2")
exit_button.place(x=37, y=490)
logout = ImageTk.PhotoImage(file='Pics\logout.png')
logout_button = Button(root, image=logout,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white", borderwidth=0, background="white", cursor="hand2")
logout_button.place(x=940, y=56)
root.mainloop()
Which arugument i should use to change the size of treeview widget ..........
use expand= True, fill = y or x to resize it.
I'm relatively new to Tkinter and I need help.
I have created a Connect database window when a button(login) is clicked from the parent window. The new window is the login.py(file). But it's not opening
connect database.py below;
from tkinter import *
from tkinter import ttk
from PIL import Image,ImageTk
import os
import pickle
import mysql.connector as sql
from tkinter import messagebox
import login
def login1():
host = host_entry.get()
port = port_entry.get()
username = username_entry.get()
password = password_entry.get()
database="cars"
spec=sql.connect(host=host,user=username,password=password,port=port)
if spec.is_connected():
messagebox.showinfo("Connected","Database connected Sucessfully")
else:
messagebox.showerror("Exists", "Database is already connected")
spec.close()
root = Tk()
root.geometry("1067x600")
root.configure(background="black")
root.resizable(False, False)
root.title("School Diaries")
#background image
bg = ImageTk.PhotoImage(file="files\Sublime Light1.jpg")
lbl_bg = Label(root,image=bg)
lbl_bg.place(x=0,y=0,relwidth=1,relheight=1)
#Labels
host_label = Label(root, text="Host Name ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 12, "bold"))
host_label.place(x=675, y=115)
host_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#host_entry.insert(0, "localhost")
host_entry.place(x=687, y=139, width=145)
port_label = Label(root, text="Port ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
port_label.place(x=675, y=190)
port_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#port_entry.insert(0, "3307")
port_entry.place(x=690, y=213, width=145)
username_label = Label(root, text="Username ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
username_label.place(x=675, y=265)
username_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#username_entry.insert(0, "root")
username_entry.place(x=687, y=287, width=145)
password_label = Label(root, text="Password ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
password_label.place(x=675, y=338)
password_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#password_entry.insert(0, "root")
password_entry.place(x=687, y=361, width=145)
#buttons
submit = ImageTk.PhotoImage(file='Pics\submit.png')
submit_button = Button(root, image=submit,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white",borderwidth=0, background="white", cursor="hand2",command=login1)
submit_button.place(x=655, y=440)
login = ImageTk.PhotoImage(file='Pics\login.png')
login_button = Button(root, image=login,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white",borderwidth=0, background="white", cursor="hand2",commmand=login)
login_button.place(x=785, y=442)
root.mainloop()
image of connect database
login.py file below ;
from tkinter import *
from tkinter import ttk
from PIL import Image,ImageTk
import os
import pickle
import mysql.connector as sql
from tkinter import messagebox
import user_inter
def login():
host = user_inter.host_entry.get()
port = user_inter.port_entry.get()
username = username_entry.get()
password = password_entry.get()
spec=sql.connect(host=host,user=username,password=password,port=port)
if spec.is_connected():
messagebox.showinfo("Connected","Database connected Sucessfully")
else:
messagebox.showerror("Exists", "Failed")
mycur=spec.cursor()
mycur.execute()
root = Tk()
root.geometry("1067x600")
root.configure(background="black")
root.resizable(False, False)
root.title("School Diaries")
#background
bg = ImageTk.PhotoImage(file="files\login.jpg")
lbl_bg = Label(root,image=bg)
lbl_bg.place(x=0,y=0,relwidth=1,relheight=1)
#Labels
login_lbl = Label(root, text="Login", bg="white", fg="#4f4e4d",font=("San Francisco", 45))
login_lbl.place(x=757,y=120)
username_label = Label(root, text="Username ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
username_label.place(x=675, y=190)
username_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#username_entry.insert(0, "root")
username_entry.place(x=695, y=215, width=190)
password_label = Label(root, text="Password ", bg="white", fg="#4f4e4d",font=("yu gothic ui", 13, "bold"))
password_label.place(x=675, y=280)
password_entry = Entry(root, highlightthickness=0, relief=FLAT, bg="white", fg="#6b6a69",font=("yu gothic ui semibold", 12))
#password_entry.insert(0, "root")
password_entry.place(x=692, y=305, width=190)
login = ImageTk.PhotoImage(file='Pics\login.png')
login_button = Button(root, image=login,font=("yu gothic ui", 13, "bold"), relief=FLAT, activebackground="white",borderwidth=0, background="white", cursor="hand2",command=login)
login_button.place(x=770, y=390)
root.mainloop()
image of login page
PS ; connect database.py is mentioned in the code as user_intern.py
0
now my doubt is ;
I have created a login.py page using tkinter and I have created a connect database.py page also, so my doubt is I have a button called login in connect database window, now the how to give argument such as if I click the login button the screen shd change to my login.py screen .....hope u understand my doubt
when I click login the login.py shd execute in the parent window itself
Thanks,
any edits in code to get my output is welcomed
when i click login in connect database the login windows shd open in parent window itself
as mentioned by #ablmmcu in comment, tkinter only has 1 root, and it should be in main program
the other point is, i suggest using tkinter.TopLevel() and use it as a window to your database when you press login button and it succeed at logging in.
more info about TopLevel:
Toplevel widgets work as windows that are directly managed by the window manager. They do not necessarily have a parent widget on top of them.
Your application can use any number of top-level windows.
source: https://www.tutorialspoint.com/python/tk_toplevel.htm
on a side note : you place TopLevel windows inside the root.
So i have written a simple tkinter gui that will show some command output results when prompted, only issue i'm having is the command wont appear on any other screen.
def updateipt():
text = Text(main_window, height=150, width=124)
text.pack()
with Popen(["iptables", '-L', '-v', '-n'], stdout=PIPE, stderr=PIPE) as p:
for line in p.stdout:
text.insert(END, line,)
text = Text(main_window, height=150, width=124)
i assumed that replacing the main_window argument above with another window would direct the text widget to a different window, but everytime i try this i get an error Which states that the window needs to be Tk(): AttributeError: 'function' object has no attribute 'tk'
How do i work around this?
Full code posted below:
#!/bin/bash
import os
import subprocess as sub
from tkinter import *
from subprocess import Popen, PIPE
def main_window():
global main_window
main_window = Tk()
main_window.title("Firewall test")
main_window.geometry("1000x700")
main_window.configure(bg="dark grey")
label1 = Label(main_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
btnproc = Button(main_window, text="Process configuration", font=('arial', 9, 'bold'), bg="light grey", fg="black",
width="30", height="2", command=lambda: process_window())
btnproc.pack(pady=20)
btnfw = Button(main_window, text="Firewall", font=('arial', 9, 'bold'), bg="light grey", fg="black", width="30",
height="2", command=lambda: firewall_window())
btnfw.pack(pady=20)
btnmon = Button(main_window, text="AIDE", font=('arial', 9, 'bold'), bg="light grey", fg="black", width="30",
height="2", command=lambda: monitor_window())
btnmon.pack(pady=20)
main_window.mainloop()
def process_window():
global process_window
process_window = Toplevel(main_window)
process_window.title("Process Configuration")
process_window.geometry("800x600")
process_window.configure(bg="dark grey")
label1 = Label(process_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
def firewall_window():
firewall_window = Toplevel(main_window)
firewall_window.title("Firewall Configuration")
firewall_window.geometry("1000x600")
firewall_window.configure(bg="dark grey")
label1 = Label(firewall_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
updatebtn = Button(firewall_window, text="View Current Iptables layout", font=('arial', 9, 'bold'), bg="light grey",
fg="black", width="30",
height="2", command=lambda: updateipt())
updatebtn.pack(pady=20)
def monitor_window():
monitor_window = Toplevel(main_window)
monitor_window.title("AIDE Configuration")
monitor_window.geometry("800x600")
monitor_window.configure(bg="dark grey")
label1 = Label(monitor_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
def updateipt():
text = Text(firewall_window, height=150, width=124)
text.pack()
with Popen(["iptables", '-L', '-v', '-n'], stdout=PIPE, stderr=PIPE) as p:
for line in p.stdout:
text.insert(END, line,)
main_window()
In your code, the name of your functions are also the name of your windows (Toplevel). Please change all your function names. Also, in your updateipt function, you are giving a function to place the Text widget so it throws an error.
import os
import subprocess as sub
from tkinter import *
from subprocess import Popen, PIPE
def main_windows():
global main_window
main_window = Tk()
main_window.title("Firewall test")
main_window.geometry("1000x700")
main_window.configure(bg="dark grey")
label1 = Label(main_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
btnproc = Button(main_window, text="Process configuration", font=('arial', 9, 'bold'), bg="light grey", fg="black",
width="30", height="2", command=lambda: process_windows())
btnproc.pack(pady=20)
btnfw = Button(main_window, text="Firewall", font=('arial', 9, 'bold'), bg="light grey", fg="black", width="30",
height="2", command=lambda: firewall_windows())
btnfw.pack(pady=20)
btnmon = Button(main_window, text="AIDE", font=('arial', 9, 'bold'), bg="light grey", fg="black", width="30",
height="2", command=lambda: monitor_windows())
btnmon.pack(pady=20)
main_window.mainloop()
def process_windows():
global process_window
process_window = Toplevel()
process_window.title("Process Configuration")
process_window.geometry("800x600")
process_window.configure(bg="dark grey")
label1 = Label(process_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
def firewall_windows():
firewall_window = Toplevel()
firewall_window.title("Firewall Configuration")
firewall_window.geometry("1000x600")
firewall_window.configure(bg="dark grey")
label1 = Label(firewall_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
updatebtn = Button(firewall_window, text="View Current Iptables layout", font=('arial', 9, 'bold'), bg="light grey",
fg="black", width="30",
height="2", command=lambda: updateipt())
updatebtn.pack(pady=20)
def monitor_windows():
monitor_window = Toplevel(main_window)
monitor_window.title("AIDE Configuration")
monitor_window.geometry("800x600")
monitor_window.configure(bg="dark grey")
label1 = Label(monitor_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
def updateipt():
text = Text(main_window, height=150, width=124)
text.pack()
with Popen(["iptables", '-L', '-v', '-n'], stdout=PIPE, stderr=PIPE) as p:
for line in p.stdout:
text.insert(END, line)
main_windows()
I don’t understand why this error appears, I have two source codes in one, everything works fine, in the second this error comes out. Looked at similar questions
but it did not give a result
try:
from Tkinter import * # for Python2
except ImportError:
from tkinter import * # for Python3
class Application(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.initialize_user_interface()
def initialize_user_interface(self):
self.master.root.title("Работа с планом")
self.master.root.geometry('400x300+200+200')
self.lbl_name = Label(root, text='Название проекта:', font=("Arial Bold", 14))
self.lbl_name.grid(column=0, row=1)
self.txt_name = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_name.grid(column=1, row=1)
self.lbl_lic = Label(root, text='Жидкость для работы:')
self.lbl_lic.grid(column=0, row=2)
self.txt_lic = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_lic.grid(column=1, row=2)
self.lbl_tank = Label(root, text='Имя танкера для работы:')
self.lbl_tank.grid(column=0, row=3)
self.txt_tank = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_tank.grid(column=1, row=3)
self.lbl_desk = Label(root, text='Описание действий сотрудника:')
self.lbl_desk.grid(column=0, row=4)
self.txt_desk = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_desk.grid(column=1, row=4)
self.lbl_agr = Label(root, text='Согласование работ с нормоконтролером:')
self.lbl_agr.grid(column=0, row=5)
self.txt_agr = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_agr.grid(column=1, row=5)
self.txt_name.focus()
self.but_b = Button(root, text="Назад", font=("Arial Bold", 14))
self.but_b.grid(column=0, row=6)
self.but_go = Button(root, text="Вперед", font=("Arial Bold", 14), command=self.safe)
self.but_go.grid(column=0, row=7)
self.but_safe = Button(root, text="Сохранить", font=("Arial Bold", 14))
self.but_safe.grid(column=1, row=6)
self.but_del = Button(root, text="Удалить", font=("Arial Bold", 14))
self.but_del.grid(column=1, row=7)
if __name__ == '__main__':
root = tk.Tk()
run = Application(root)
Application(root)
root.mainloop()
Firstly, when you are changing the Root Title and geometry, you do not need to call the root simply leaving it as self.master.geometry('400x300+200+200') will work fine.
Secondly, when using from tkinter import * you do not need to use tk.Frame you can just use Frame as Python will recognise this as a class name.
Thirdly one of your button commands self.safe will cause an error because this method is not defined nor is it a built in Tk command.
Improved code...
from tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.master = master
self.initialize_user_interface()
def initialize_user_interface(self):
self.master.title("Работа с планом")
self.master.geometry('400x300+200+200')
self.lbl_name = Label(root, text='Название проекта:', font=("Arial Bold", 14))
self.lbl_name.grid(column=0, row=1)
self.txt_name = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_name.grid(column=1, row=1)
self.lbl_lic = Label(root, text='Жидкость для работы:')
self.lbl_lic.grid(column=0, row=2)
self.txt_lic = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_lic.grid(column=1, row=2)
self.lbl_tank = Label(root, text='Имя танкера для работы:')
self.lbl_tank.grid(column=0, row=3)
self.txt_tank = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_tank.grid(column=1, row=3)
self.lbl_desk = Label(root, text='Описание действий сотрудника:')
self.lbl_desk.grid(column=0, row=4)
self.txt_desk = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_desk.grid(column=1, row=4)
self.lbl_agr = Label(root, text='Согласование работ с нормоконтролером:')
self.lbl_agr.grid(column=0, row=5)
self.txt_agr = Entry(root, width=50, font=("Arial Bold", 14))
self.txt_agr.grid(column=1, row=5)
self.txt_name.focus()
self.but_b = Button(root, text="Назад", font=("Arial Bold", 14))
self.but_b.grid(column=0, row=6)
self.but_go = Button(root, text="Вперед", font=("Arial Bold", 14), command=None)
self.but_go.grid(column=0, row=7)
self.but_safe = Button(root, text="Сохранить", font=("Arial Bold", 14))
self.but_safe.grid(column=1, row=6)
self.but_del = Button(root, text="Удалить", font=("Arial Bold", 14))
self.but_del.grid(column=1, row=7)
if __name__ == '__main__':
root = Tk()
run = Application(root)
Application(root)
root.mainloop()
I am trying to create a timer in tkinter. It count down from set time and then output "Time is up". I have written most of my code. I also have inserted a logging system, so I can work over some errors, which are recorded into a log file.
Code:
from tkinter import *
import logging
logging.basicConfig(filename='timer_err.log',format='%(levelname)s:%(message)s',level=logging.DEBUG)
main = Tk()
main.wm_attributes("-fullscreen",True)
main.wm_attributes("-transparentcolor","darkgreen")
main.title("Timer")
main.config(background="orange")
timerun = 0
comp = 0
secs = DoubleVar()
mins = IntVar()
hrs = IntVar()
def ok():
global timerun
try:
comp = float(float(secs.get())+int(mins.get()*60)+int(hrs.get()*3600))
done.config(state="disabled")
logging.info(("\t{} - Program launched").format(asctime(localtime())))
while timerun < comp:
timerun = clock()
disp.config(state="normal")
disp.insert(0, str(round(comp-timerun, 3)))
main.update()
disp.delete(0, END)
disp.config(state="readonly")
disp.config(state="normal")
disp.insert(0, "Time is up!")
disp.config(state="readonly")
main.update()
def end(self):
main.destroy()
logging.info(("\t{} - Program successfully terminated").format(asctime(localtime())))
main.bind("<Escape>",end)
except Exception as e:
logging.debug(("\t{} - {}").format(asctime(localtime()),str(e)))
logging.warning(("\t{} - {}").format(asctime(localtime()),str(e)))
pass
finally:
logging.info(("\t{} - Program stopped").format(asctime(localtime())))
dispframe = Frame(main, bg="orange")
dispframe.pack(fill="both")
disp = Entry(dispframe, fg="black", bg="lightgray", font=("Arial", 100, "bold"), bd=0, state="readonly", takefocus=False, readonlybackground="lightgray", selectforeground="white", selectbackground="navy")
disp.pack(fill="x", pady=12, side="left")
setframe = Frame(main, bg="orange")
setframe.pack(fill="both")
seconds = Spinbox(setframe, fg="red", bg="yellow", from_=0, to=59.5, increment=0.5, font=("Arial", 100, "bold"), bd=0, state="readonly", takefocus=True, readonlybackground="yellow", buttonbackground="green", selectforeground="white", selectbackground="navy", wrap=True, textvariable=secs)
seconds.pack(fill="x", pady=12)
minutes = Spinbox(setframe, fg="red", bg="yellow", from_=0, to=59, font=("Arial", 100, "bold"), bd=0, state="readonly", takefocus=True, readonlybackground="yellow", buttonbackground="green", selectforeground="white", selectbackground="navy", wrap=True, textvariable=mins)
minutes.pack(fill="x", pady=12)
hours = Spinbox(setframe, fg="red", bg="yellow", from_=0, to=99999, font=("Arial", 100, "bold"), bd=0, state="readonly", takefocus=True, readonlybackground="yellow", buttonbackground="green", selectforeground="white", selectbackground="navy", wrap=True, textvariable=hrs)
hours.pack(fill="x", pady=12)
okframe = Frame(main, bg="orange")
okframe.pack(fill="both")
done = Button(okframe, fg="red", bg="yellow", text="Done", font=("Arial", 100, "bold"), bd=0, activeforeground="red", activebackground="yellow", underline=1, command=ok)
done.pack(fill="x", pady=12)
from time import *
main.mainloop()
Could someone help me to create a "Reset" button, which sets time back to 0?
Or at least give me a slight advice to me on how to do that. Thank you.