Why a function to customise ttk.Style() not work? - python

I can't figure out the cause of why function customise_ttk_widgets_style(ss) is causing the ttk.Button and ttk.Labels to not appear correctly. Commenting out line # s = customise_ttk_style(s) avoids the wrong widget appearances but I don't understand why this is so. Can you explain the cause and remedy of the issue? Thanks.
import tkinter as tk
import tkinter.ttk as ttk
BG = '#3b3b39'
FG = 'white'
DFONT = ('URW Gothic L', '10', 'Normal')
def customise_ttk_widgets_style(ss):
# All Widgets
ss.configure(".", font=DFONT, background=BG, foreground=FG, cap=tk.ROUND,
join=tk.ROUND)
# main ttk.Frame
ss.configure('Main.TFrame', background='pink') # For debugging
# Default ttk.Button
ss.configure('TButton', padding=5, relief=tk.FLAT)
ss.map('TButton',
foreground=[("disabled", 'grey'), ('pressed', 'red'),
('active', 'yellow')],
background=[('disabled', '#646a67'), ('pressed', '!focus', BG),
('active', '#535553')],
relief=[('pressed', 'sunken'), ('!pressed', 'raised')],
)
return ss
if __name__ == "__main__":
root = tk.Tk()
root['background'] = BG
s = ttk.Style()
s = customise_ttk_widgets_style(s) # This function is causing problem
button = ttk.Button(root, text="ttk.Button (!disabled)")
dbutton = ttk.Button(root, text="ttk.Button (disabled)")
dbutton.state(['!disabled', 'disabled'])
label = ttk.Label(root, text="ttk.Label (!disabled)")
dlabel = ttk.Label(root, text="ttk.Label (disabled)")
dlabel.state(['!disabled', 'disabled'])
button.grid(row=0, column=0)
dbutton.grid(row=0, column=1)
label.grid(row=1, column=0)
dlabel.grid(row=1, column=1)
root.mainloop()
Correct appearance:
Wrong appearance:

Finally figured out the issue. The definition of DFONT was wrong. It ought to be defined as:
from tkinter import font
DFONT = font.Font(family='URW Gothic L', size=10, weight='bold')
But this definition can't be a global variable as tk.Tk() needs to be first defined. If DFONT is to be a global variable, it ought to be defined as a dict() object, i.e.
DFONT = dict(family='URW Gothic L', size=10, weight='bold')
Thereafter, in the customise_ttk_widgets_style() function, instead of
ss.configure(".", font=DFONT, background=BG, foreground=FG,
cap=tk.ROUND, join=tk.ROUND)
the correct syntax is:
ss.configure(".", font=font.Font(**DFONT), background=BG, foreground=FG,
cap=tk.ROUND, join=tk.ROUND)
The corrected script:
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import font
BG = '#3b3b39'
FG = 'white'
DFONT = dict(family='URW Gothic L', size=10, weight='bold')
def customise_ttk_widgets_style(ss):
# All Widgets
ss.configure(".", font=font.Font(**DFONT), background=BG, foreground=FG,
cap=tk.ROUND, join=tk.ROUND)
# main ttk.Frame
ss.configure('Main.TFrame', background='pink') # For debugging
# Default ttk.Button
ss.configure('TButton', padding=5, relief=tk.FLAT)
ss.map('TButton',
foreground=[("disabled", 'grey'), ('pressed', 'red'),
('active', 'yellow')],
background=[('disabled', '#646a67'), ('pressed', '!focus', BG),
('active', '#535553')],
relief=[('pressed', 'sunken'), ('!pressed', 'raised')],
)
return ss
if __name__ == "__main__":
root = tk.Tk()
root['background'] = BG
s = ttk.Style()
s = customise_ttk_widgets_style(s)
button = ttk.Button(root, text="ttk.Button (!disabled)")
dbutton = ttk.Button(root, text="ttk.Button (disabled)")
dbutton.state(['!disabled', 'disabled'])
label = ttk.Label(root, text="ttk.Label (!disabled)")
dlabel = ttk.Label(root, text="ttk.Label (disabled)")
dlabel.state(['!disabled', 'disabled'])
button.grid(row=0, column=0)
dbutton.grid(row=0, column=1)
label.grid(row=1, column=0)
dlabel.grid(row=1, column=1)
root.mainloop()

Related

choose one color of two for object and when click on button, then starts drawing with turle in python

`I am creating a loging page where user needs to choose color(objekta krāsa) for car. User need to chose from
blue(Zilā krāsa) and black(melnā krāsa) colors in the drop down menu and when button "Ienākt" is clicked it starts shoud start drawing a car with selected,but now when i pres ienākt it shows blank page and also when both drop down menus are emty its still works and doesnt show error. I been trying to fix this for all evening, and i still learning.How to get that when users choses color and clicks ienākt buttom drawing starts at he chosen color?and when all the menus are emty it should not work.
i would appreciate your help!
from tkinter import *
from tkinter import messagebox
import tkinter as tk
from tkinter import ttk
import turtle
root = Tk()
root .title('Ienākt')
root .geometry('925x500+300+200')
root. configure(bg="#fff")
root .resizable(False, False)
img = PhotoImage(file=r'C:\Users\Inga\Downloads\ienakt.png')
Label(root, image=img, bg='white').place(x=5, y=50)
frame = Frame(root, width=350, height=400, bg="white")
frame. place(x=480, y=70)
heading = Label(frame, text='Ienākt', fg='#57a1f8', bg='white',
font=('Microsoft YaHei UI Light', 23, 'bold'))
heading.place(x=100, y=5)
# -----
def on_enter(e):
user.delete(0, 'end')
def on_leave(e):
name = user.get()
if name == '':
user.insert(0, 'E-pasts')
user = Entry(frame, width=25, fg='#000000', border=0,
bg="white", font=('Microsoft YaHei UI Light', 11))
user.place(x=30, y=80)
user.insert(0, 'E-pasts')
user.bind('<FocusIn>', on_enter)
user.bind('<FocusOut>', on_leave)
Frame(frame, width=295, height=2, bg='#000000').place(x=25, y=107)
# -----
def on_enter(e):
password.delete(0, 'end')
def on_leave(e):
name = password.get()
if name == '':
password.insert(0, 'Parole')
password = Entry(frame, width=25, fg='#000000', border=0,
bg="white", font=('Microsoft YaHei UI Light', 11))
password.place(x=30, y=150)
password.insert(0, 'Parole')
password.bind('<FocusIn>', on_enter)
password.bind('<FocusOut>', on_leave)
Frame(frame, width=295, height=2, bg='#000000').place(x=25, y=177)
# ----tekts krasa
label = Label(root, text="Objekta krāsa", width=41,
font=("Microsoft YaHei UI Light", 11), bg='white')
label.place(x=467, y=291)
# ---IZVĒLE-krāsa
col = tk.StringVar()
col_chs = ttk.Combobox(frame, width=45, textvariable=col, state='readonly')
col_chs['values'] = ('Melnā krāsa', 'Zilā krāsa')
col_chs.place(x=25, y=249)
Frame(frame, width=295, height=2, bg='#000000').place(x=25, y=247)
# ----objekts
label = Label(root, text="Objekts", width=41,
font=("Microsoft YaHei UI Light", 11), bg='white')
label.place(x=467, y=361)
# ----Izvēle-- objekts
col = tk.StringVar()
col_chs = ttk.Combobox(frame, width=45, textvariable=col, state='readonly')
col_chs['values'] = ('Mašīna',)
col_chs.place(x=25, y=318)
Frame(frame, width=295, height=2, bg='#000000').place(x=25, y=317)
# ----
def draw_object():
screen = turtle.Screen()
color = col_chs.get()
car = turtle.Turtle()
if color == 'Melnā krāsa':
car.color("black")
car.fillcolor("black")
car.begin_fill()
car.forward(370)
car.left(90)
car.forward(50)
car.left(90)
car.forward(370)
car.left(90)
car.forward(50)
car.end_fill()
# Below code for drawing window and roof
car.penup()
car.goto(100, 50)
car.pendown()
car.setheading(45)
car.forward(70)
car.setheading(0)
car.forward(100)
car.setheading(-45)
car.forward(70)
car.setheading(90)
car.penup()
car.goto(200, 50)
car.pendown()
car.forward(49.50)
car.penup()
car.goto(100, -10)
car.pendown()
car.begin_fill()
car.circle(20)
car.end_fill()
car.penup()
car.goto(300, -10)
car.pendown()
car.begin_fill()
car.circle(20)
car.end_fill()
turtle.exitonclick()
elif color == 'Zilā krāsa':
car.color("blue")
car.fillcolor("blue")
car.penup()
car.goto(0, 0)
car.pendown()
car.begin_fill()
car.forward(370)
car.left(90)
car.forward(50)
car.left(90)
car.forward(370)
car.left(90)
car.forward(50)
car.end_fill()
# Below code for drawing window and roof
car.penup()
car.goto(100, 50)
car.pendown()
car.setheading(45)
car.forward(70)
car.setheading(0)
car.forward(100)
car.setheading(-45)
car.forward(70)
car.setheading(90)
car.penup()
car.goto(200, 50)
car.pendown()
car.forward(49.50)
car.penup()
car.goto(100, -10)
car.pendown()
car.begin_fill()
car.circle(20)
car.end_fill()
car.penup()
car.goto(300, -10)
car.pendown()
car.begin_fill()
car.circle(20)
car.end_fill()
turtle.exitonclick()
# ---
def login():
user_name = user.get()
user_password = password.get()
if user_name == "E-pasts" or user_password == "Parole":
messagebox.showerror("Kļūda", "Aizpildiet visus laukus")
else:
if user_name == "admin" and user_password == "admin":
messagebox.showinfo("Paziņojums", "Ienācāt")
draw_object()
turtle.mainloop()
else:
messagebox.showerror("Kļūda", "Nepareizs e-pasts vai parole")
# ---- ieiešanas poga
login_button = Button(frame, width=41, pady=7,
text='Ienākt', bg='#57a1f8', fg='white', command=draw_object)
login_button["command"] = draw_object
login_button.place(x=23, y=360)
def open_login_page():
exec(open("path/to/login_page_code.py").read())
root.mainloop()
`
At first i tried to make when button is clicked it call the draw function and then draw and then i added if and elif in the draw_object and try to change some little things but that didnt help.
i would appreciate your help!

How Can I integrate Python Turtle into Tkinter

from tkinter import *
import turtle
def RunTurtle():
import turtle
window = turtle.Screen()
window.bgcolor("light green")
window.title("Turtle")
t = turtle.Turtle()
t.speed(20)
def MyTurtleFunc(Fl, Sl, f, rin, ro, c, w):
t.color(c)
t.width(w)
for _ in range(Fl):
for _ in range(Sl):
t.forward(f)
t.right(rin)
t.right(ro)
MyTurtleFunc(36, 4, 100, 90, 10, "blue", 4)
def RunGUI():
master = Tk()
master.title("Project")
canvas = Canvas(master, height=1080, width=1920)
canvas.pack()
def RUN():
RunTurle()
TopFrame = Frame(master, bg='light green')
TopFrame.place(relx=0.04, rely=0.04, relwidth=0.91, relheight=0.6)
MiddleFrame = Frame(master, bg='light blue')
MiddleFrame.place(relx=0.04, rely=0.66, relwidth=0.91, relheight=0.06)
BottomFrame = Frame(master, bg='orange')
BottomFrame.place(relx=0.04, rely=0.74, relwidth=0.91, relheight=0.25)
TopLabel = Label(TopFrame, bg='light green', text="Drawing Robot", font="calibri 15 bold", foreground="black")
TopLabel.pack(padx=5, pady=5)
LabelBottom = Label(BottomFrame, bg='orange', text="Debug Area ", font="vendara 15 bold ", foreground="black")
LabelBottom.pack(padx=0.1, pady=0.1)
LabelBottomText = Text(BottomFrame, height=10.5, width=180)
LabelBottomText.tag_configure('style', foreground='grey', font=('calibri', 10, 'bold'))
LabelBottomText.pack()
fronttext = "..."
LabelBottomText.insert(END, fronttext, 'style')
RunProgram = Button(MiddleFrame, text="RUN PROGRAM", foreground="black", command=RUN)
RunProgram.pack(padx=0.2, pady=0.2, side=LEFT)
master.mainloop()
I designed interface my entry level program.I divide this three part.TopFrame must show turtle.Middle Frame has button which help us to start the program .Bottom Frame has debug area. I want to integrate "RunTurtle()" function into TopFrame.When the user click "RUN PROGRAM" button ,interface will open and turtle will draw pattern into TopFrame.How can I do this ? thank you...
def RUN():
RunTurle()
should be
def RUN():
RunTurtle()
and run the function RunGUI() its works

How to format the text input from Text Widget in Tkinter

In my tkinter program I'm collecting text from the user using Text widget, this is later printed on the screen using a label widget. Although I'm able to print it onto the screen, the text is all center aligned. Since what I'm collecting is a procedure for something it gets difficult to read, so I need it to be left aligned.
This is my Procedure method -
Once the procedure is collected it is stored into a dictionary
def Procedure(self):
textfield = Text(gui, height=30, width=82)
textfield.place(x="20", y="100")
procedure_label = LabelWidget(self.screen, "Procedure", "Courier", 40)
procedure_label.Call().place(x="220", y="20")
button_save = Button(gui, text="Next", padx="50", pady="20", bg="lightgrey",
command=partial(self.CheckPage, 4, procedure=textfield))
button_save.place(x="250", y="600")
This is how I'm printing my proceudre
proc_text_label = ""
for i in fullDictProc:
proc_text_label_temp = Label(root, text=i, wraplength=900)
proc_text_label = proc_text_label_temp
proc_text_label.config(font=("Courier", 12))
proc_text_label.place(x=70, y=250)
Here is a minimal reproducible code to demonstrate the problem
Run it and see the alignment of the text.
from tkinter import *
from functools import partial
gui = Tk()
gui.geometry("700x700")
def printit(textfield):
procedure_list = [textfield.get("1.0", "end-1c")]
textfield.place_forget()
proc_text_label = ""
for i in procedure_list:
proc_text_label_temp = Label(gui, text=i, wraplength=900)
proc_text_label = proc_text_label_temp
proc_text_label.config(font=("Courier", 12))
proc_text_label.place(x=70, y=250)
textfield = Text(gui, height=30, width=82)
textfield.place(x="20", y="100")
button_save = Button(gui, text="Next", padx="50", pady="20", bg="lightgrey",
command=partial(printit, textfield))
button_save.place(x=500, y=600)
gui.mainloop()
I think what you are looking for might be justify:
proc_text_label.config(justify='left')
Have a look at The Tkinter Label Widget
I think what you're looking for is the anchor parameter.
This is how it worked with your minimal example:
from tkinter import *
from functools import partial
gui = Tk()
gui.geometry("700x700")
def printit(textfield):
procedure_list = [textfield.get("1.0", "end-1c")]
textfield.place_forget()
proc_text_label = ""
for i in procedure_list:
proc_text_label_temp = Label(gui, text=i, wraplength=900,
anchor='w',
bg='blue',
width=50)
proc_text_label = proc_text_label_temp
proc_text_label.config(font=("Courier", 12))
proc_text_label.place(x=70, y=250)
textfield = Text(gui, height=30, width=82)
textfield.place(x="20", y="100")
button_save = Button(gui, text="Next", padx="50", pady="20", bg="lightgrey",
command=partial(printit, textfield))
button_save.place(x=500, y=600)
gui.mainloop()

How to get a float number in input GUI

I am new to python trying to make a simple converter app, but my problem is i can't figure out how to solve the km to m. If i figure this out I can figure out the rest. Thanks in advance! Here's my code
import tkinter from tkinter import ttk
window=tkinter.Tk()
window.title("Conversion Unit")
labelOne=ttk.Label(window, text='Enter Value')
labelOne.grid(row=0, column=0)
to_be_converted=ttk.Combobox(
values=('mm', 'cm', 'inches', 'feet', 'yards', 'meter', 'km', 'miles'),
width=10
).grid(row=0, column=2)
labelTwo=ttk.Label(window, text="Equivalent to")
labelTwo.grid(row=1, column=1)
converted=ttk.Combobox(
values=('mm', 'cm', 'inches', 'feet', 'yards', 'meter', 'km', 'miles'),
width=10
).grid(row=1, column=2)
userName=tkinter.DoubleVar()
userEntry=ttk.Entry(window, width=5, textvariable=userName)
userEntry.grid(row=0, column=1)
def convert():
if to_be_converted.get=='km' and converted.get=='m':
labelTwo.configure(text='Value is equivalent to:' + userName.get() * 1000)
btn=ttk.Button(window, text='Convert!', command=convert)
btn.grid(row=0, column=4)
window.mainloop()
Here's a working version, there are a few changes:
import tkinter
from tkinter import ttk
UNITS = ('mm', 'cm', 'inches','feet', 'yards', 'meter', 'km', 'miles')
window = tkinter.Tk()
window.title("Conversion Unit")
labelOne = ttk.Label(window,text='Enter Value')
labelOne.grid(row=0,column=0)
to_be_converted = ttk.Combobox(values=UNITS, width=10)
to_be_converted.grid(row=0, column=2)
labelTwo = ttk.Label(window, text="Equivalent to")
labelTwo.grid(row=1,column=1)
converted = ttk.Combobox(values=UNITS, width=10)
converted.grid(row=1, column=2)
userName = tkinter.DoubleVar()
userEntry = ttk.Entry(window, width=5, textvariable = userName)
userEntry.grid(row=0, column=1)
def convert():
if to_be_converted.get() == 'km' and converted.get() == 'meter':
labelTwo.configure(text='Value is equivalent to:' + str(userName.get()*1000))
btn = ttk.Button(window, text='Convert!', command=convert)
btn.grid(row=0, column=4)
window.mainloop()
.grid() returns None
So this line:
to_be_converted = ttk.Combobox(values=UNITS, width=10).grid(row=0, column=2 )
Has to be:
to_be_converted = ttk.Combobox(values=UNITS, width=10)
to_be_converted.grid(row=0, column=2)
(same with converted)
.get is a bound method, not an attribute
So this line:
if to_be_converted.get == 'km' and converted.get == 'meter':
has to be:
if to_be_converted.get() == 'km' and converted.get() == 'meter':
(and 'm' has to be replaced with 'meter' -- or UNITS has to have 'm', not 'meter').
Can't concatenate string with float
So this line:
labelTwo.configure(text='Value is equivalent to:' + userName.get()*1000)
Has to be, for example:
labelTwo.configure(text='Value is equivalent to:' + str(userName.get()*1000))

An unexpected window appears in tkinter python

I made a separate file called clinic1.py for the other code and import it to the main page. Everything works fine however another window appears when I click save button on the add new item page.
When I place all the code on the main page that small window doesn't appear.
I cant find whats causing another window to appear when it's in a separate file.
This is my main page:
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
large_font = ('Verdana',12)
storedusername =['foo'] storedpass=['123'] storedretype=[]
list_of_users=storedusername
list_of_passwords=storedpass
def all_clinic_frames(event):
combo_clinic=combo.get()
if combo_clinic == 'Clinic 1':
enter()
root = Tk()
root.geometry('800x600')
root.title('CSSD')
topFrame=Frame(root,width=800,height=100,padx=310)
area=Label(topFrame,text='CSSD')
area.config(font=("Courier", 50))
frame=Frame(root,highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100, bd= 0)
frame.place(relx=.5, rely=.5, anchor="center")
username = Label(frame, text='User Name') username.config(font='Arial',width=15) password = Label(frame, text='Password') password.config(font='Arial',width=15) enteruser = Entry(frame, textvariable=StringVar(),font=large_font) enterpass = Entry(frame, show='*', textvariable=StringVar(),font=large_font)
combo_choice=StringVar()
combo=ttk.Combobox(frame,textvariable=combo_choice)
combo['values']=('Clinic 1')
combo.state(['readonly'])
combo.grid(row=0,sticky=NW)
combo.set('Choose Area...')
combo.bind('<<ComboboxSelected>>',all_clinic_frames)
topFrame.grid(row=0,sticky=N) topFrame.grid_propagate(False) area.grid(row=0,column=1,sticky=N) username.grid(row=1, sticky=E) enteruser.grid(row=1, column=1) password.grid(row=2, sticky=E) enterpass.grid(row=2, column=1)
def valid():
usernameRight=enteruser.get()
passwordRight=enterpass.get()
while True:
try:
if (usernameRight==list_of_users[0]) and (passwordRight==list_of_passwords[0]):
import clinic1
clinic1.main_page()
quit()
break
except IndexError:
invalid = Label(frame, text='User name or Password is incorrect!', fg='red')
invalid.grid(row=3, columnspan=2)
break
def enter():
register = Button(frame, text='Sign In',relief=RAISED,fg='white',bg='red',command=valid)
register.grid(row=3,column=1,ipadx=15,sticky=E)
def quit():
root.destroy()
And this is the second file that I imported in the main page which i saved as clinic1.py
from tkinter import*
import tkinter.messagebox
newInstList=[]
def addItem(event=None):
global back_add,quantityentry,itemEntry,itemEntry1,quantityentry1
itemFrameTop=Frame(root, width=800,height=100,bg='pink')
itemFrameTop.grid_propagate(False)
itemFrameTop.grid(row=0)
area1_item = Label(itemFrameTop, text='CSSD', pady=5,padx=230)
area1_item.config(font=("Courier", 30))
area1_item.grid_propagate(False)
area1_item.grid(row=0,column=1,sticky=NE)
clinic_1 = Label(itemFrameTop, text='Clinic 1', bg='red', fg='white', bd=5)
clinic_1.config(font=("Courier", 15))
clinic_1.grid_propagate(False)
clinic_1.grid(row=1, sticky=W,padx=10)
itemFrameMid=Frame(root,width=700,height=600,bg='blue')
itemFrameMid.grid_propagate(False)
itemFrameMid.grid(row=1)
itemname=Label(itemFrameMid,text='Item name:')
itemname.config(font=('Arial,15'))
itemname.grid_propagate(False)
itemname.grid(row=1,sticky=E)
quantity=Label(itemFrameMid,text='Qty:')
quantity.config(font=('Arial,15'))
quantity.grid_propagate(False)
quantity.grid(row=1,column=3, sticky=E,padx=10)
itemEntry=Entry(itemFrameMid)
itemEntry.config(font=('Arial,15'))
itemEntry.grid(row=1,column=1,sticky=EW,padx=30,pady=10)
itemEntry1 = Entry(itemFrameMid)
itemEntry1.config(font=('Arial,15'))
itemEntry1.grid(row=2, column=1)
quantityentry=Entry(itemFrameMid,width=5)
quantityentry.config(font=('Arial',15))
quantityentry.grid(row=1, column=4)
quantityentry1 = Entry(itemFrameMid, width=5)
quantityentry1.config(font=('Arial', 15))
quantityentry1.grid(row=2, column=4,padx=10)
"""When I click save button another small window appears"""
okbutton = Button(itemFrameMid, text='Save', command=saveCheck)
okbutton.config(font=('Arial', 12))
okbutton.grid(row=3, column=4, padx=15)
back_add = Label(itemFrameTop, text='Back')
back_add.config(font=('Courier,15'))
back_add.grid(row=0, sticky=W, padx=30)
back_add.bind('<Button-1>', main_page)
back_add.bind('<Enter>', red_text_back1)
back_add.bind('<Leave>', black_text_back1)
def saveCheck():
saveQuestion=tkinter.messagebox.askquestion('CSSD', 'Are you sure you want to save?')
if saveQuestion == 'yes':
newInstList.append(itemEntry.get())
newInstList.append(quantityentry.get())
newInstList.append(itemEntry1.get())
newInstList.append(quantityentry1.get())
print(newInstList)
main_page()
elif saveQuestion == 'no':
pass
def red_text_back1(event=None):
back_add.config(fg='red')
def black_text_back1(event=None):
back_add.config(fg='black')
def red_text_add(event=None):
addnew.config(fg='red')
def black_text_add(event=None):
addnew.config(fg='black')
def main_page(event=None):
global addnew,usedInst,logOut
frame1 = Frame(root, width=800, height=100,bg='pink')
frame1.grid(row=0, column=0, sticky="nsew")
frame1.grid_propagate(False)
midframe1=Frame(root,width=800,height=600)
midframe1.grid_propagate(False)
midframe1.grid(row=1)
area1 = Label(frame1, text='CSSD',pady=5,padx=350)
area1.config(font=("Courier", 30))
area1.grid(row=0)
clinic1=Label(frame1,text='Clinic 1',bg='red',fg='white',bd=5)
clinic1.config(font=("Courier", 15))
clinic1.grid_propagate(False)
clinic1.grid(row=1,sticky=W,padx=10)
addnew=Label(midframe1,text='+ Add new item')
addnew.config(font=('Arial',15))
addnew.grid(row=2,column=1,sticky=E,ipadx=50)
addnew.bind('<Button-1>', addItem)
addnew.bind('<Enter>', red_text_add)
addnew.bind('<Leave>', black_text_add)
root = Tk()
root.geometry('800x600')
Both files have this line of code:
root = Tk()
Each time you do that, you get another root window. A tkinter application needs to have exactly one instance of Tk running at a time.
You need to remove the last two lines from clinic1.py. You will also need to pass in the reference to root to any methods from clinic1.py that need it.
First file.
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
large_font = ('Verdana',12)
storedusername =['foo']
storedpass=['123']
storedretype=[]
list_of_users=storedusername
list_of_passwords=storedpass
def all_clinic_frames(event):
combo_clinic=combo.get()
if combo_clinic == 'Clinic 1':
enter()
root = Tk()
root.geometry('800x600')
root.title('CSSD')
topFrame=Frame(root,width=800,height=100,padx=310)
area=Label(topFrame,text='CSSD')
area.config(font=("Courier", 50))
frame=Frame(root,highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100, bd= 0)
frame.place(relx=.5, rely=.5, anchor="center")
myvar=StringVar()
username = Label(frame, text='User Name')
username.config(font='Arial',width=15)
password = Label(frame, text='Password')
password.config(font='Arial',width=15)
enteruser = Entry(frame, textvariable=myvar, font=large_font)
pass1=StringVar()
enterpass = Entry(frame, show='*', textvariable=pass1, font=large_font)
combo_choice=StringVar()
combo=ttk.Combobox(frame,textvariable=combo_choice)
combo['values']=[('Clinic 1')]
combo.state(['readonly'])
combo.grid(row=0,sticky=NW)
combo.set('Choose Area...')
combo.bind('<<ComboboxSelected>>',all_clinic_frames)
topFrame.grid(row=0,sticky=N)
topFrame.grid_propagate(False)
area.grid(row=0,column=1,sticky=N)
username.grid(row=1, sticky=E)
enteruser.grid(row=1, column=1)
password.grid(row=2, sticky=E)
enterpass.grid(row=2, column=1)
def valid():
usernameRight=enteruser.get()
passwordRight=enterpass.get()
while True:
try:
if (usernameRight==list_of_users[0]) and (passwordRight==list_of_passwords[0]):
import clinic1
clinic1.main_page(root)
# quit()
break
except IndexError:
invalid = Label(frame, text='User name or Password is incorrect!', fg='red')
invalid.grid(row=3, columnspan=2)
break
def enter():
register = Button(frame, text='Sign In',relief=RAISED,fg='white',bg='red',command=valid)
register.grid(row=3,column=1,ipadx=15,sticky=E)
def quit():
root.destroy()
root.mainloop()
clinic1.py
from tkinter import*
import tkinter.messagebox
newInstList=[]
def addItem(root, event=None):
global back_add,quantityentry,itemEntry,itemEntry1,quantityentry1
if event is None:
event = Event()
itemFrameTop=Frame(root, width=800, height=100, bg='pink')
itemFrameTop.grid_propagate(False)
itemFrameTop.grid(row=0)
area1_item = Label(itemFrameTop, text='CSSD', pady=5,padx=230)
area1_item.config(font=("Courier", 30))
area1_item.grid_propagate(False)
area1_item.grid(row=0,column=1,sticky=NE)
clinic_1 = Label(itemFrameTop, text='Clinic 1', bg='red', fg='white', bd=5)
clinic_1.config(font=("Courier", 15))
clinic_1.grid_propagate(False)
clinic_1.grid(row=1, sticky=W,padx=10)
itemFrameMid=Frame(root,width=700,height=600,bg='blue')
itemFrameMid.grid_propagate(False)
itemFrameMid.grid(row=1)
itemname=Label(itemFrameMid,text='Item name:')
itemname.config(font=('Arial,15'))
itemname.grid_propagate(False)
itemname.grid(row=1,sticky=E)
quantity=Label(itemFrameMid,text='Qty:')
quantity.config(font=('Arial,15'))
quantity.grid_propagate(False)
quantity.grid(row=1,column=3, sticky=E,padx=10)
itemEntry=Entry(itemFrameMid)
itemEntry.config(font=('Arial,15'))
itemEntry.grid(row=1,column=1,sticky=EW,padx=30,pady=10)
itemEntry1 = Entry(itemFrameMid)
itemEntry1.config(font=('Arial,15'))
itemEntry1.grid(row=2, column=1)
quantityentry=Entry(itemFrameMid,width=5)
quantityentry.config(font=('Arial',15))
quantityentry.grid(row=1, column=4)
quantityentry1 = Entry(itemFrameMid, width=5)
quantityentry1.config(font=('Arial', 15))
quantityentry1.grid(row=2, column=4,padx=10)
"""When I click save button another small window appears"""
okbutton = Button(itemFrameMid, text='Save', command=lambda: saveCheck(root))
okbutton.config(font=('Arial', 12))
okbutton.grid(row=3, column=4, padx=15)
back_add = Label(itemFrameTop, text='Back')
back_add.config(font=('Courier,15'))
back_add.grid(row=0, sticky=W, padx=30)
back_add.bind('<Button-1>', main_page)
back_add.bind('<Enter>', red_text_back1)
back_add.bind('<Leave>', black_text_back1)
def saveCheck(root):
saveQuestion=tkinter.messagebox.askquestion('CSSD', 'Are you sure you want to save?')
if saveQuestion == 'yes':
newInstList.append(itemEntry.get())
newInstList.append(quantityentry.get())
newInstList.append(itemEntry1.get())
newInstList.append(quantityentry1.get())
print(newInstList)
main_page(root)
elif saveQuestion == 'no':
pass
def red_text_back1(event=None):
back_add.config(fg='red')
def black_text_back1(event=None):
back_add.config(fg='black')
def red_text_add(event=None):
addnew.config(fg='red')
def black_text_add(event=None):
addnew.config(fg='black')
def main_page(root):
global addnew,usedInst,logOut
frame1 = Frame(root, width=800, height=100,bg='pink')
frame1.grid(row=0, column=0, sticky="nsew")
frame1.grid_propagate(False)
midframe1=Frame(root,width=800,height=600)
midframe1.grid_propagate(False)
midframe1.grid(row=1)
area1 = Label(frame1, text='CSSD',pady=5,padx=350)
area1.config(font=("Courier", 30))
area1.grid(row=0)
clinic1=Label(frame1,text='Clinic 1',bg='red',fg='white',bd=5)
clinic1.config(font=("Courier", 15))
clinic1.grid_propagate(False)
clinic1.grid(row=1,sticky=W,padx=10)
addnew=Button(midframe1,text='+ Add new item', font=('Arial', 15), command=lambda: addItem(root))
addnew.grid(row=2,column=1,sticky=E,ipadx=50)
# addnew.bind('<Button-1>', lambda r=root: addItem(r))
addnew.bind('<Enter>', red_text_add)
addnew.bind('<Leave>', black_text_add)

Categories