How to get a float number in input GUI - python

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))

Related

in tkinter how do i get a number into an entry

Im a beginner in Python and running into the following problem:
for an assignment i need to get the number that gets inserted into text1, then when i push the button pk<<<kw multiply it by 1.36 and insert it into text2. and reverse by pressing the other button.
only i have no clue how.
from tkinter import *
root= Tk()
root.title("python programma omrekenen")
root.geometry("300x200")
def Iets():
label = Label(text="vermogen in pk:")
label.place(x=50,y=50)
text1=IntVar()
entry1=Entry(textvariable=text1)
entry1.place(x=150,y=50)
x1=text1.get()
def Functie 10:
def Functie 11:
button=Button (text="PK>>>KW", command=Functie10)
button.place (x=50,y=100)
button=Button (text="PK<<<KW", command=functie11)
button.place (x=150,y=150)
label = Label(text="vermogen in KW:")
label.place(x=50,y=150)
text2=IntVar()
entry2=Entry(textvariable=text2)
entry2.place(x=150,y=150)
x2=text2.get()
root.mainloop()
sorry for the bad english
That little code should hopefully help you out :
from tkinter import *
root = Tk()
root.title("python programma omrekenen")
root.geometry("300x200")
def Iets():
Entry1 = Entry(root, bd=4)
Entry1.grid(row=1, column=2)
Entry1.delete(0, END)
Entry1.insert(0, "Insert number")
Entry2 = Entry(root, bd=4)
Entry2.grid(row=2, column=2)
Entry2.insert(0, "Result")
def multiply(entry: int):
if entry == 1:
Entry2.delete(0, END)
try:
Entry2.insert(0, f"{int(Entry1.get()) * 2}")
except ValueError:
Entry2.insert(0, f"Invalid value")
Entry1.delete(0, END)
if entry == 2:
Entry1.delete(0, END)
try:
Entry1.insert(0, f"{int(Entry2.get()) * 2}")
except ValueError:
Entry1.insert(0, f"Invalid value")
Entry2.delete(0, END)
Button1 = Button(root, text='Multiply', bd=2, bg='green', command=lambda: multiply(1))
Button1.grid(row=1, column=1)
Button2 = Button(root, text='Multiply', bd=2, bg='green', command=lambda: multiply(2))
Button2.grid(row=2, column=1)
Iets()
root.mainloop()
Not sure if thats what you ment by reverse it but yeah.. its easy to understand so you should be fine !
command is used to call a function.
In your case , it does a multiplication on a number and gets inserted into an entry field.
Also , delete & insert are 2 tkinter methods clear & insert the data respectively
from tkinter import *
root= Tk()
root.title("python programma omrekenen")
root.geometry("300x400")
text1=IntVar()
text2=IntVar()
def first():
entry2.delete(0,END)
entry2.insert(0,text1.get()*1.36)
def second():
entry1.delete(0,END)
entry1.insert(0,text2.get()*1.36)
label = Label(text="vermogen in pk:")
label.place(x=50,y=50)
entry1=Entry(textvariable=text1)
entry1.place(x=150,y=50)
button=Button (text="PK>>>KW", command=first)
button.place (x=50,y=100)
button=Button (text="PK<<<KW", command=second)
button.place (x=50,y=200)
label = Label(text="vermogen in KW:")
label.place(x=50,y=150)
entry2=Entry(textvariable=text2)
entry2.place(x=150,y=150)
root.mainloop()

How do I create or move a Tkinter widget when a checkbutton is clicked but the widget has to be in two different places based on what is clicked?

So I'm trying to create a tkinter GUI and I want an entry widget to appear in one location if 'Yes' is selected on a list, and then an alternate location if 'No' is selected. I am also having a problem with clearing my entry boxes and removing the widgets that appear when 'Yes' is selected. It is supposed to be a interest collecting form that writes info input by the user to send an email to them after directing them to other resources and such. Is there an alternate way I should go about handling the logic other than if statements? I am relatively new to python and I got to this point and I don't know how to solve it.
import pandas as pd
from openpyxl import load_workbook
from tkinter import *
import tkinter as tk
import shutil
from PIL import Image, ImageTk
from tkinter import font
writer = pd.ExcelWriter('1511Application.xlsx', engine='xlsxwriter')
#writing bulk data
df = pd.DataFrame({'Name': [''], 'Email': [''], 'Subject': [''], 'Message': [''], 'Grade': [''], 'Mechanical': [''], 'Electrical': [''], 'Marketing': [''], 'Graphic Design': [''], 'Programming': [''], 'Chairmans': ['']})
df.to_excel(writer, sheet_name='Sheet1', index=False)
writer.save()
root = Tk()
root.title('FIRST team 1511 - Rolling Thunder Student Interest Form')
root.iconbitmap('1511Icon.ico')
root.geometry("800x500+0+0")
photo = PhotoImage(file="1511logo3.png")
teamlogo = Label(root, image=photo)
Titlefont = font.Font(family='Helvetica', size=14, weight='bold')
font.families()
tk.Label(root, text="FIRST Team 1511 - Rolling Thunder \n Student Interest form", font=Titlefont).place(x=150, y=20)
tk.Label(root, text="Name:", bg='red3', fg='black', width=25,height=1).place(x=130, y=80)
tk.Label(root, text="Email:", bg='red3', fg='black', width=25, height=1).place(x=130,y=110)
tk.Label(root, text="Have you been in FIRST before?", bg='red3', fg='black', width=25, height=1).place(x=130,y=170)
tk.Label(root, text="Grade:", bg="red3", fg='black', width=25, height=1).place(x=130,y=140)
interest_label = tk.Label(root, text="What are you most interested in?", bg="red3", fg="black", width=25, height=1)
interest_label.place(x=130,y=200)
#dropdown event handling
def selected(event):
global other_expand_failsafe2
entrydisplay = clicked.get()
if 'Yes' in entrydisplay:
global extrainfo
extrainfo = tk.Entry(root, width=32)
extrainfo.place(x=312,y=201)
extra_label = tk.Label(root, text='If yes, what team and level of FIRST?', width=28, height=1, bg='red3', fg='black')
extra_label.place(x=110, y=200)
interest_label.place(x=130,y=230)
interest_mechanical.place(x=311, y=228)
interest_electrical.place(x=311, y=248)
interest_marketing.place(x=311, y=268)
interest_design.place(x=311, y=288)
interest_programming.place(x=311, y=308)
interest_chairmans.place(x=311, y=328)
interest_advocacy.place(x=311, y=348)
interest_leadership.place(x=311, y=368)
interest_video_production.place(x=311, y=388)
interest_social_media.place(x=311, y=408)
other_checkbox.place(x=311, y=428)
extrainfo_on = "1"
else:
#This is for when "No" is selected and Other is checked
other_expand_failsafe = "1"
extrainfo_on = "0"
#entrybox next to other checkbox
def expand():
other.set("1")
other_expand = other.get() #other=1 basically
global other_entry
global other_entry1
if "1" in other_expand:
other_entry = tk.Entry(root, width=30)
other_entry.place(x=371, y=430)
if "1" in other_expand and other_expand_failsafe:
other_entry.place(x=371, y=430)
def OtherClear():
if '0' in other_expand_failsafe2:
other_entry.place(x=798, y=400)
def ExtraInfoClear():
if "1" in extrainfo_on:
extrainfo.place(x=312,y=201)
extra_label.place(x=110, y=200)
else:
pass
def Submit():
df = pd.DataFrame({'Name': [f"{name.get()}"], 'Email': [f"{email.get()}"], 'Subject': ['Thanks for coming to our event!'], 'Message': ['Test'], 'Grade': [f"{int(grade.get())}"], 'Mechanical': [f"{mechanical.get()}"], 'Electrical': [f"{electrical.get()}"], 'Marketing': [f"{marketing.get()}"], 'Graphic Design': [f"{design.get()}"], 'Programming': [f"{programming.get()}"], 'Chairmans': [f"{chairmans.get()}"]})
writer = pd.ExcelWriter('1511Application.xlsx', engine='openpyxl')
writer.book = load_workbook('1511Application.xlsx')
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
reader = pd.read_excel(r'1511Application.xlsx')
df.to_excel(writer, index=False, header=False, startrow=len(reader)+1)
writer.close()
name.delete(0, END)
email.delete(0, END)
FIRST.delete(0, END)
grade.delete(0,END)
extrainfo.delete(0,END)
interest_mechanical.deselect()
interest_electrical.deselect()
interest_marketing.deselect()
interest_design.deselect()
interest_programming.deselect()
interest_chairmans.deselect()
interest_advocacy.deselect()
interest_leadership.deselect()
interest_social_media.deselect()
interest_video_production.deselect()
other_checkbox.deselect()
#set failsafe2 to 0 to hide entry box
other_expand_failsafe2 = "0"
OtherClear()
ExtraInfoClear()
def Clear():
name.delete(0, END)
email.delete(0, END)
clicked.set(options[1])
grade.delete(0, END)
interest_mechanical.deselect()
interest_electrical.deselect()
interest_marketing.deselect()
interest_design.deselect()
interest_programming.deselect()
interest_chairmans.deselect()
interest_advocacy.deselect()
interest_leadership.deselect()
interest_social_media.deselect()
interest_video_production.deselect()
other_checkbox.deselect()
extrainfo.delete(0, END)
other_entry.delete(0,END)
#set failsafe2 to 0 to hide entry box
other_expand_failsafe2 = "0"
OtherClear()
submit_button = tk.Button(root, text="Submit", width=10, command=Submit, padx=10, pady=10, bg='red3', fg='black')
submit_button.place(x=20, y=450)
clear_button = tk.Button(root, text="Clear Form", width=10, command=Clear, padx=12, pady=10, bg='red3', fg='black')
clear_button.place(x=570, y=450)
info = StringVar()
name = tk.Entry(root, width=30, textvariable=info)
name.place(x=311,y=81)
email = tk.Entry(root, width=30)
email.place(x=311,y=111)
#DROPDOWN BASE CODE
options = [
'Yes',
'No'
]
clicked = StringVar()
clicked.set(options[1])
#ENDS ABOVE
FIRST = tk.OptionMenu(root, clicked, *options, command=selected)
FIRST.place(x=311, y=165)
grade = tk.Entry(root, width=30)
grade.place(x=311, y=140)
mechanical = IntVar()
electrical = IntVar()
marketing = IntVar()
design = IntVar()
programming = IntVar()
chairmans= IntVar()
advocacy = IntVar()
leadership = IntVar()
video_production = IntVar()
social_media = IntVar()
other = StringVar()
other.set("0")
interest_mechanical = tk.Checkbutton(root, text="Mechanical", variable=mechanical)
interest_electrical = tk.Checkbutton(root, text="Electrical", variable=electrical)
interest_marketing = tk.Checkbutton(root, text="Marketing", variable=marketing)
interest_design = tk.Checkbutton(root, text="Graphic Design", variable=design)
interest_programming = tk.Checkbutton(root, text="Programming", variable=programming)
interest_chairmans = tk.Checkbutton(root, text="Public Speaking/Chairmans", variable=chairmans)
interest_advocacy = tk.Checkbutton(root, text='Government Advocacy', variable=advocacy)
interest_leadership = tk.Checkbutton(root, text='Leadership', variable=leadership)
interest_video_production = tk.Checkbutton(root, text='Video Production', variable=video_production)
interest_social_media = tk.Checkbutton(root,text='Social Media', variable=social_media)
other_checkbox = tk.Checkbutton(root, text='Other', variable=other, command=expand)
interest_mechanical.place(x=311, y=198)
interest_electrical.place(x=311, y=218)
interest_marketing.place(x=311, y=238)
interest_design.place(x=311, y=258)
interest_programming.place(x=311, y=278)
interest_chairmans.place(x=311, y=298)
interest_advocacy.place(x=311, y=318)
interest_leadership.place(x=311, y=338)
interest_video_production.place(x=311, y=358)
interest_social_media.place(x=311, y=378)
other_checkbox.place(x=311, y=398)
teamlogo.place(x=520, y=20)
root.mainloop()

Problem in clearing frame using tkinter python

I am new to tkinter Python module and creating a very simple UI with tkinter.
Its basically a optical card which will first ask for card number. User can enter "Card1 or Card2". For Card1 there is one more edit which ask for KM range like 10KM, 40KM, 80KM and user can enter the value specified and it gives the optimal value and acceptable value.
Code is working fine. Only problem is with clearing the information using clear button for Card1. I am not able to clear the complete information for Card1 which includes clearing the edit box and outout.
Below is the code
from tkinter import *
from tkinter import ttk
import tkinter
frm = Tk()
frm.geometry('600x400')
frm.title("Optical Power Specs")
bg = "#94FB9E"
fnt = 'tahoma 15 bold'
frm.config(bg=bg)
frm.resizable(False, False)
#frm.iconbitmap('f.gif')
frame = Frame(frm, bg=bg)
frame2 = Frame(frm, bg=bg)
frame4 = Frame(frm, bg=bg)
def f():
global lbl104080
global frame3
global txt104080
if str(txt1.get()) == 'Card1':
print("entered ehre")
frame3 = Frame(frm, bg=bg)
frame3.grid(row=3, column=0)
txt104080 = Entry(frame3, textvariable=sv104080)
lbl104080 = Label(frame3, text="Enter 10KM or 40KM or 80KM ", font='None 10', background=bg, padx=0)
lbl104080.grid(row=1, column=0, pady=30)
txt104080.grid(row=1, column=1)
if str(txt104080.get()) == '10KM':
lblr['text'] = ("""
Optimal Value = -10 To -10 dBm
Acceptable Value = -10 To -10 dBm
""")
elif str(txt104080.get()) == '40KM':
lblr['text'] = ("""
Optimal Value = -40 To -40 dBm
Acceptable Value = -40 To 40 dBm
""")
elif str(txt1.get()) == 'Card2':
lblr['text'] = ("""
Optimal Value = -2 To -2 dBm
Acceptable Value = -2 To -2 dBm
""")
elif str(txt1.get()) == 'A1236':
lblr['text'] = ("""
Optimal Value = -100 To -20 dBm
Acceptable Value = -3 To 1 dBm
""")
def clea():
# global lbl104080
#lbl104080['text'] = ('')
txt104080['text'] = ('')
lbl104080.destroy()
frame3.grid_forget()
frame3.destroy()
#frame3.destroy()
lblr['text'] = ('')
sv104080 = StringVar()
opt = ttk.Label(frm, text='Optical Power Specs', font=fnt, background=bg)
Ent = ttk.Label(frame, text='Enter BOM Code OR Card Name', font='None 10', background=bg)
btnok = ttk.Button(frame2, text='OK', command=f)
btncancel = ttk.Button(frame2, text='Clear', command=clea)
lblr = ttk.Label(frame4, font='None 10', background=bg)
svname_bom = StringVar()
txt1 = Entry(frame, textvariable=svname_bom)
opt.grid(row=0, column=0, pady=5, padx=200)
frame.grid(row=1, column=0)
Ent.grid(row=0, column=0, padx=10, pady=20)
txt1.grid(row=0, column=1)
frame2.grid(row=2, column=0)
btnok.grid(row=0, column=0, padx=10, pady=20)
btncancel.grid(row=0, column=1, pady=20)
frame4.grid(row=4, column=0)
lblr.grid(row=2, column=0, pady=50, padx=100)
frm.mainloop()
Please help me to solve this issue
You probably want txt1.delete(0, 'end') that will delete all text from main entry text
def clea():
#lbl104080['text'] = ('')
txt104080['text'] = ('')
txt1.delete(0, 'end')
lbl104080.destroy()
frame3.grid_forget()
frame3.destroy()
#frame3.destroy()
lblr['text'] = ('')

How to reconfig Tkinter scrolled text

I have this situation where I need to make the scrolledText as readonly, so the user can only add values to it through a button, like the following:
from tkinter import *
from tkinter import scrolledtext
startingWin = Tk()
myEntry = Entry(startingWin, font=("Courier",25, "bold"), width=15)
myScrolledText = scrolledtext.ScrolledText(startingWin, font=("Courier",25, "bold"),width=15, height=3, state='disabled')
def addEntryContentToScrolledText(entry, scrolledText):
entryValue = str((entry.get()).strip())
scrolledtext.config(state='normal')
if entryValue not in str(scrolledText.get('1.0', 'end-1c')) and entryValue != "":
scrolledText.insert(INSERT, (entryValue + "\n"))
scrolledtext.config(state='disabled')
myAddButton = Button(startingWin, text="Add")
myAddButton.config(command=lambda: addEntryContentToScrolledText(myEntry, myScrolledText))
myScrolledText.grid(row=0, column=1)
myEntry.grid(row=0, column=0)
myAddButton.grid(row=1, column=0)
startingWin.mainloop()
However, I get this error AttributeError: module 'tkinter.scrolledtext' has no attribute 'config'
How can I reconfigure the scrolledText?
Your widget name is myScrolledText, not scrolledtext: (scrolledtext is the imported module name)
from tkinter import *
from tkinter import scrolledtext
startingWin = Tk()
myEntry = Entry(startingWin, font=("Courier",25, "bold"), width=15)
myScrolledText = scrolledtext.ScrolledText(startingWin, font=("Courier",25, "bold"),width=15, height=3, state='disabled')
def addEntryContentToScrolledText(entry, textwidget):
entryValue = str((entry.get()).strip())
textwidget.configure(state='normal')
if entryValue not in str(textwidget.get('1.0', 'end-1c')) and entryValue != "":
textwidget.insert(INSERT, (entryValue + "\n"))
textwidget.configure(state='disabled')
myAddButton = Button(startingWin, text="Add", command=lambda: addEntryContentToScrolledText(myEntry, myScrolledText))
myScrolledText.grid(row=0, column=1)
myEntry.grid(row=0, column=0)
myAddButton.grid(row=1, column=0)
startingWin.mainloop()

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