I have a code made with pyamaze library which I perform 4 different types of search on maze and I want to display it with GUI (to make the user choose the type of search they want)
but the problem when I run the code the GUI gets stuck
from pyamaze import maze, COLOR, agent,textLabel
#Depth first search
def DFS(m1):
start=(m1.rows,m1.cols)
explored=[start]
frontier=[start]
dfsPath={}
while len(frontier)>0:
currCell=frontier.pop()
if currCell==(1,1):
break
for d in 'ESNW':
if m1.maze_map[currCell][d]==True:
if d=='E':
childCell=(currCell[0],currCell[1]+1)
elif d=='W':
childCell=(currCell[0],currCell[1]-1)
elif d=='S':
childCell=(currCell[0]+1,currCell[1])
elif d=='N':
childCell=(currCell[0]-1,currCell[1])
if childCell in explored:
continue
explored.append(childCell)
frontier.append(childCell)
dfsPath[childCell]=currCell
fwdPath={}
cell=(1,1)
while cell!=start:
fwdPath[dfsPath[cell]]=cell
cell=dfsPath[cell]
return fwdPath
#Breadth first search
def BFS(m2):
start=(m2.rows,m2.cols)
frontier=[start]
explored=[start]
bfsPath={}
while len(frontier)>0:
currCell=frontier.pop(0)
if currCell==(1,1):
break
for d in 'ESNW':
if m2.maze_map[currCell][d]==True:
if d=='E':
childCell=(currCell[0],currCell[1]+1)
elif d=='W':
childCell=(currCell[0],currCell[1]-1)
elif d=='N':
childCell=(currCell[0]-1,currCell[1])
elif d=='S':
childCell=(currCell[0]+1,currCell[1])
if childCell in explored:
continue
frontier.append(childCell)
explored.append(childCell)
bfsPath[childCell]=currCell
fwdPath={}
cell=(1,1)
while cell!=start:
fwdPath[bfsPath[cell]]=cell
cell=bfsPath[cell]
return fwdPath
# A-star search
from queue import PriorityQueue
def h(cell1,cell2):
x1,y1=cell1
x2,y2=cell2
return abs(x1-x2)+abs(y1-y2)
def aStar(m3):
start=(m3.rows,m3.cols)
g_score={cell:float('inf') for cell in m3.grid}
g_score[start]=0
f_score={cell:float('inf') for cell in m3.grid}
f_score[start]=h(start,(1,1))
open=PriorityQueue()
open.put((h(start,(1,1)),h(start,(1,1)),start))
aPath={}
while not open.empty():
currCell=open.get()[2]
if currCell==(1,1):
break
for d in 'ESNW':
if m3.maze_map[currCell][d]==True:
if d=='E':
childCell=(currCell[0],currCell[1]+1)
if d=='W':
childCell=(currCell[0],currCell[1]-1)
if d=='N':
childCell=(currCell[0]-1,currCell[1])
if d=='S':
childCell=(currCell[0]+1,currCell[1])
temp_g_score=g_score[currCell]+1
temp_f_score=temp_g_score+h(childCell,(1,1))
if temp_f_score < f_score[childCell]:
g_score[childCell]=temp_g_score
f_score[childCell]=temp_f_score
open.put((temp_f_score,h(childCell,(1,1)),childCell))
aPath[childCell]=currCell
fwdPath={}
cell=(1,1)
while cell!=start:
fwdPath[aPath[cell]]=cell
cell=aPath[cell]
return fwdPath
#uniform cost search.
def UCS(m,*h,start=None):
if start is None:
start=(m.rows,m.cols)
hurdles=[(i.position,i.cost) for i in h]
unvisited={n:float('inf') for n in m.grid}
unvisited[start]=0
visited={}
revPath={}
while unvisited:
currCell=min(unvisited,key=unvisited.get)
visited[currCell]=unvisited[currCell]
if currCell==m._goal:
break
for d in 'EWNS':
if m.maze_map[currCell][d]==True:
if d=='E':
childCell=(currCell[0],currCell[1]+1)
elif d=='W':
childCell=(currCell[0],currCell[1]-1)
elif d=='S':
childCell=(currCell[0]+1,currCell[1])
elif d=='N':
childCell=(currCell[0]-1,currCell[1])
if childCell in visited:
continue
tempDist= unvisited[currCell]+1
for hurdle in hurdles:
if hurdle[0]==currCell:
tempDist+=hurdle[1]
if tempDist < unvisited[childCell]:
unvisited[childCell]=tempDist
revPath[childCell]=currCell
unvisited.pop(currCell)
fwdPath={}
cell=m._goal
while cell!=start:
fwdPath[revPath[cell]]=cell
cell=revPath[cell]
return fwdPath,visited[m._goal]
from timeit import timeit
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import tkinter as tk
class MazeGUI:
def __init__(self, master):
self.master = master
self.master.title("Maze GUI")
self.master.geometry("700x500")
self.master.resizable(True, True)
self.master.configure(background='white')
self.create_widgets()
self.master.mainloop()
def create_widgets(self):
self.frame = tk.Frame(self.master, bg='black')
self.frame.pack(fill=tk.BOTH, expand=True)
self.frame.grid_rowconfigure(0, weight=1)
self.frame.grid_columnconfigure(0, weight=1)
self.frame.grid_propagate(False)
self.button1 = tk.Button(self.frame, text="BFS", command=self.bfs)
self.button1.grid(row=1, column=1, sticky="nsew", padx=10, pady=10)
self.button1.place(x=50,y=50)
self.button2 = tk.Button(self.frame, text="A*", command=self.aStar)
self.button2.grid(row=2, column=1, sticky="nsew", padx=10, pady=10)
self.button3 = tk.Button(self.frame, text="UCS", command=self.UCS)
self.button3.grid(row=3, column=1, sticky="nsew", padx=10, pady=10)
self.button4 = tk.Button(self.frame, text="DFS", command=self.dfs)
self.button4.grid(row=4, column=1, sticky="nsew", padx=10, pady=10)
self.button5 = tk.Button(self.frame, text="Exit", command=self.exit)
self.button5.grid(row=5, column=1, sticky="nsew", padx=10, pady=10)
def bfs(self):
m2=maze()
m2.CreateMaze()
path=BFS(m2)
b=agent(m2,footprints=True,filled=True)
m2.tracePath({b:path})
l2=textLabel(m2,'Length of Shortest Path',len(path)+1)
m2.mainloop()
def aStar(self):
m3=maze()
m3.CreateMaze()
path=aStar(m3)
c=agent(m3,footprints=True)
m3.tracePath({c:path})
l3=textLabel(m3,"A Star Path Length",len(path)+1)
m3.mainloop()
def UCS(self):
m4=maze(10,10)
m4.CreateMaze()
path,c=UCS(m4)
textLabel(m4,'Total Cost',c)
a=agent(m4,color=COLOR.cyan,filled=True,footprints=True,)
m4.tracePath({a:path},delay=100)
t1=timeit(stmt='UCS(m4)',number=100,globals=globals())
textLabel(m4,'UCS Time',t1)
m4.run()
m4.mainloop()
def dfs(self):
m1=maze()
m1.CreateMaze()
path=DFS(m1)
a=agent(m1,footprints=True)
m1.tracePath({a:path})
l1=textLabel(m1,'Length of Shortest Path',len(path)+1)
m1.mainloop()
def exit(self):
self.master.destroy()
if __name__ == '__main__':
root = tk.Tk()
app = MazeGUI(root)
I want to be displayed correctly and As it meant to be so if a press a button the search starts and agent moves.
Related
I'm working on a tkinter drag and drop app, my code is working just fine but only at one condition:
that the dragged text widget, when selected to be moved, is not under the cursor (so if the text widget is dragged by a word it doesn't work).
I've tried to fix the issue by adding some negative value to the y axis to make the selection always a little bit above, but it kinda create a weird distance if the text widget is dragged by the bottom.
So I was wondering if there is a better way to add some space.
Also I'd like to show the "Not empty" error only when the text is dragged in the self.dad_text
and is not empty, while right now it appear for every text widget. Is there a way to fix that?
This is my code
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.first_list = ["11:00", "03:43", "22:04", "17:21", "22:35", "07:01", "16:11", "09:00"]
self.second_list = ["morning\nmorning\nmorning", "afternoon\nafternoon\nafternoon", "evening\nevening\nevening", "nigth\nnight\nnight"]
self.w_list = []
self.first_frame = tk.Frame(root)
self.first_frame.pack(padx=15, pady=15, fill="both", expand="true", side="left", anchor="w")
self.second_frame = tk.Frame(root)
self.second_frame.pack(padx=15, pady=15, fill="both", expand="true", side="left")
self.up()
def up(self):
for n, hour in enumerate(self.first_list):
self.list_one_frame = tk.LabelFrame(self.first_frame)
self.list_one_frame.grid(row=n, column=0, padx=10, pady=10)
self.one_text = tk.Text(self.list_one_frame, width=10, height=2)
self.one_text.grid(row=0, column=0,padx=10, pady=10)
self.one_text.insert("end", hour)
self.one_text.config(state="disabled")
self.dad_text = tk.Text(self.list_one_frame, width=20, height=1)
self.dad_text.grid(row=0, column=1, padx=10, pady=10, ipady=7)
for n, day in enumerate(self.second_list):
self.second_text = tk.Text(self.second_frame, width=9, height=3)
self.second_text.grid(row=n, column=1, pady=10, padx=10)
self.second_text.insert("end", day)
self.second_text.bind('<Button-1>', self.click)
self.second_text.bind('<B1-Motion>',self.drag)
self.second_text.bind('<ButtonRelease-1>',self.release)
def click(self, event):
self.widget_check = event.widget
self.text = event.widget.get("1.0",'end-1c')
root.clipboard_clear()
root.clipboard_append(self.text)
self.top = tk.Toplevel(root)
self.top.attributes('-alpha', 0.7)
self.top.overrideredirect(True)
self.top._offsetx = event.x
self.top._offsety = event.y
x = self.top.winfo_pointerx() - self.top._offsetx
y = self.top.winfo_pointery() - self.top._offsety - 50
self.top.geometry('+{x}+{y}'.format(x=x,y=y))
label = tk.Label(self.top, text=self.text)
label.grid(row=0, column=0)
def drag(self,event):
widget = event.widget.winfo_containing(event.x_root, event.y_root)
x = self.top.winfo_pointerx() - self.top._offsetx
y = self.top.winfo_pointery() - self.top._offsety - 50
self.top.geometry(f"+{x}+{y}")
def release(self, event):
widget = event.widget.winfo_containing(event.x_root, event.y_root)
try:
if widget.get('1.0', 'end-1c') != "":
messagebox.showerror("Error", "Not empty")
else:
reference_clipboard = root.clipboard_get()
widget.config(state="normal")
widget.insert("end", f"{reference_clipboard}")
widget.config(state="disabled")
self.top.destroy()
except:
self.top.destroy()
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()
Thank you!
I have a for loop that is meant to run through a list, display some items in tkinter, wait for a button to be pushed, and then store some Entry and Checkbutton data. The code below is a MRE of the basics of what I'm trying to do. In the case below, when the Button is hit, I want to return to the loop_function and gather the variables from the button_function.
I thought perhaps using something like lambda: continue or lambda: return might bring it back to the first function, but those throw errors.
Any ideas?
from tkinter import *
class TestClass(Frame):
def __init__(self, parent=None):
self.parent = parent
Frame.__init__(self)
self.main = self.master
self.f = Frame(self.parent)
self.f.pack()
(Button(self.f, text='Start',
command = self.loop_function)
.grid(column=0, row=0, padx=10, pady=10))
def loop_function(self):
name_list = ['Luke', 'Han', 'Leia', 'Chewie']
for n in name_list:
self.button_function(n)
force_user = self.fu.get()
side = self.sd.get()
print(n, force_user, side)
def button_function(self, n):
self.fu = IntVar(value=1)
self.sd = StringVar(value='rebel')
self.fu_e = Checkbutton(self.f, variable=self.fu)
self.sd_e = Entry(self.f, textvariable=self.sd)
col = 0
lbl_list = ['Name', 'Force User?', 'Side']
for l in lbl_list:
(Label(self.f, text=l, width=11, anchor=W)
.grid(column=col, row=0, padx=10, pady=10))
col += 1
(Label(self.f, text=n, width=11, anchor=W)
.grid(column=0, row=1, padx=5))
self.fu_e.grid(column=1, row=1)
self.sd_e.grid(column=2, row=1)
(Button(self.f, text='Save',
command = lambda: print('WAIT HERE!!'))
.grid(column=1, row=2, padx=10, pady=10))
if __name__ == '__main__':
root=Tk()
ui = TestClass(root)
ui.pack()
root.mainloop()
I think the following code does what you want to do.
After clicking on the button Start the user gets a dialog where she can enter properties of the first user Luke. By clicking on the button Save the entered data is stored in some way. Then the properties of the next user (Han) can be edited.
A for loop is not the correct approach here. Instead we want to listen for the click events of the start and save buttons. In my solution, when the user clicks Start, the event handler pick_next_player is being called. This method always picks the next element from an iterator that I wrapped around name_list. Then the GUI elements are being rendered with your button_function.
The event handler save_action listens to the click event of the Save button. It collects the values that the user entered, stores it into self.results and displays the next player by calling pick_next_player.
When the last player has been saved, this script just prints a line 'finished ...' to the console. I assume you are going to stop the script or close the dialog there. But this is of course up to you.
from tkinter import *
class TestClass(Frame):
def __init__(self, parent=None):
self.parent = parent
Frame.__init__(self)
self.main = self.master
self.f = Frame(self.parent)
self.f.pack()
(
Button(self.f, text='Start', command=self.pick_next_player)
.grid(column=0, row=0, padx=10, pady=10)
)
self.name_list = ['Luke', 'Han', 'Leia', 'Chewie']
self.name_iter = iter(self.name_list)
self.results = []
self.current_name = None
def pick_next_player(self):
try:
self.current_name = next(self.name_iter)
except StopIteration:
print(f"finished: {self.results}")
return
self.button_function()
def button_function(self):
self.fu = IntVar(value=1)
self.sd = StringVar(value='rebel')
self.fu_e = Checkbutton(self.f, variable=self.fu)
self.sd_e = Entry(self.f, textvariable=self.sd)
col = 0
lbl_list = ['Name', 'Force User?', 'Side']
for l in lbl_list:
(Label(self.f, text=l, width=11, anchor=W)
.grid(column=col, row=0, padx=10, pady=10))
col += 1
(
Label(self.f, text=self.current_name, width=11, anchor=W)
.grid(column=0, row=1, padx=5)
)
self.fu_e.grid(column=1, row=1)
self.sd_e.grid(column=2, row=1)
(
Button(self.f, text='Save', command=self.save_action)
.grid(column=1, row=2, padx=10, pady=10)
)
def save_action(self):
force_user = self.fu.get()
side = self.sd.get()
print(f"saving {self.current_name}, {force_user}, {side}")
self.results.append({'name': self.current_name, 'force': force_user, 'faction': side})
self.pick_next_player()
if __name__ == '__main__':
root = Tk()
ui = TestClass(root)
ui.pack()
root.mainloop()
I have the following code for stop watch. when you run it, you can see an stop watch with start button.
I have another code for calculation of long equations which takes a long time to solve. How can I put that code inside of the following code: when I run the code the stop watch start counting automatically and when the code finished its calculation, stopwatch stop counting.
import tkinter
import time
class StopWatch(tkinter.Frame):
#classmethod
def main(cls):
tkinter.NoDefaultRoot()
root = tkinter.Tk()
root.title('Stop Watch')
root.resizable(True, False)
root.grid_columnconfigure(0, weight=1)
padding = dict(padx=5, pady=5)
widget = StopWatch(root, **padding)
widget.grid(sticky=tkinter.NSEW, **padding)
root.mainloop()
def __init__(self, master=None, cnf={}, **kw):
padding = dict(padx=kw.pop('padx', 5), pady=kw.pop('pady', 5))
super().__init__(master, cnf, **kw)
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(1, weight=1)
self.__total = 0
self.__label = tkinter.Label(self, text='Total Time:')
self.__time = tkinter.StringVar(self, '0.000000')
self.__display = tkinter.Label(self, textvariable=self.__time)
self.__button = tkinter.Button(self, text='Start', command=self.__click)
self.__label.grid(row=0, column=0, sticky=tkinter.E, **padding)
self.__display.grid(row=0, column=1, sticky=tkinter.EW, **padding)
self.__button.grid(row=1, column=0, columnspan=2,
sticky=tkinter.NSEW, **padding)
def __click(self):
if self.__button['text'] == 'Start':
self.__button['text'] = 'Stop'
self.__start = time.clock()
self.__counter = self.after_idle(self.__update)
else:
self.__button['text'] = 'Start'
self.after_cancel(self.__counter)
def __update(self):
now = time.clock()
diff = now - self.__start
self.__start = now
self.__total += diff
self.__time.set('{:.6f}'.format(self.__total))
self.__counter = self.after_idle(self.__update)
if __name__ == '__main__':
StopWatch.main()
thank you so much
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)
l would like to create a control system for administrator on Tkinter and some functions (add, delete, update and load) are main part of control system but when l run the code , these functions do not work and there is no error message. But ,l could not figure out where the problem is. My code is still not completed yet. İf l solve it, then l will move to another step.
import tkinter
from tkinter import *
userlist = [
['Meyers', '12356'],
['Smith','abcde'],
['Jones','123abc34'],
['Barnhart','12//348'],
['Nelson','1234'],
["Prefect",'1345'],
["Zigler",'8910'],
['Smith','1298']]
def domain():
def whichSelected () :
print ("At %s of %d" % (select.curselection(), len(userlist)))
return int(select.curselection()[0])
def addEntry():
userlist.append ([nameVar.get(), passwordVar.get()])
setSelect()
def updateEntry():
userlist[whichSelected()] = [nameVar.get(), passwordVar.get()]
setSelect()
def deleteEntry():
del userlist[whichSelected()]
setSelect()
def loadEntry():
name, password = userlist[whichSelected()]
nameVar.set(name)
passwordVar.set(password)
def makeWindow():
win=Tk()
global nameVar, passwordVar, select
frame1 = Frame(win)
frame1.pack()
Label(frame1, text="Name").grid(row=0, column=0, sticky=W)
nameVar = StringVar()
name = Entry(frame1, textvariable=nameVar)
name.grid(row=0, column=1, sticky=W)
Label(frame1, text="Password").grid(row=1, column=0, sticky=W)
passwordVar= StringVar()
password= Entry(frame1, textvariable=passwordVar)
password.grid(row=1, column=1, sticky=W)
frame2 = Frame(win) # Row of buttons
frame2.pack()
b1 = Button(frame2,text=" Add ",command=addEntry)
b2 = Button(frame2,text="Update",command=updateEntry)
b3 = Button(frame2,text="Delete",command=deleteEntry)
b4 = Button(frame2,text=" Load ",command=loadEntry)
b1.pack(side=LEFT); b2.pack(side=LEFT)
b3.pack(side=LEFT); b4.pack(side=LEFT)
frame3 = Frame(win) # select of names
frame3.pack()
scroll = Scrollbar(frame3, orient=VERTICAL)
select = Listbox(frame3, yscrollcommand=scroll.set, height=6)
scroll.config (command=select.yview)
scroll.pack(side=RIGHT, fill=Y)
select.pack(side=LEFT, fill=BOTH, expand=1)
return win
def setSelect():
userlist.sort()
select.delete(0,END)
for name in userlist:
select.insert(END,name)
win=makeWindow()
setSelect()
win.mainloop()
page1=Tk()
but1=Button(page1,text="Domain",command=domain).pack()
It is bad practice to define your functions in a function and makes debugging pretty difficult. I would start by using an object to create this GUI. Object variables:
passwordVar and nameVar,
select
userlist
win
There's a lot going wrong for your code.
For instance, you don't need to import tkinter twice. Your casing of the variable names doesn't follow PEP8. You could benefit from an OOP approach.
I would suggest finding a good IDE to code in that can highlight your formatting and errors.
Take a look at the provided code:
import tkinter as tk
user_list = [
['Meyers', '12356'],
['Smith','abcde'],
['Jones','123abc34'],
['Barnhart','12//348'],
['Nelson','1234'],
["Prefect",'1345'],
["Zigler",'8910'],
['Smith','1298']]
class Domain(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.name_var = tk.StringVar()
self.password_var = tk.StringVar()
self.make_window()
def which_selected(self):
print("At %s of %d" % (self.select.curselection(), len(user_list)))
return int(self.select.curselection()[0])
def add_entry(self):
user_list.append([self.name_var.get(), self.password_var.get()])
self.set_select()
def update_entry(self):
user_list[self.which_selected()] = [
self.name_var.get(), self.password_var.get()]
self.set_select()
def delete_entry(self):
del user_list[self.which_selected()]
self.set_select()
def load_entry(self):
name, password = user_list[self.which_selected()]
self.name_var.set(name)
self.password_var.set(password)
def make_window(self):
frame1 = tk.Frame(self.parent)
frame1.pack()
tk.Label(frame1, text="Name").grid(row=0, column=0, sticky=tk.W)
name = tk.Entry(frame1, textvariable=self.name_var)
name.grid(row=0, column=1, sticky=tk.W)
tk.Label(frame1, text="Password").grid(row=1, column=0, sticky=tk.W)
password = tk.Entry(frame1, textvariable=self.password_var)
password.grid(row=1, column=1, sticky=tk.W)
frame2 = tk.Frame(self.parent) # Row of buttons
frame2.pack()
b1 = tk.Button(frame2, text=" Add ", command=self.add_entry)
b2 = tk.Button(frame2, text="Update", command=self.update_entry)
b3 = tk.Button(frame2, text="Delete", command=self.delete_entry)
b4 = tk.Button(frame2, text=" Load ", command=self.load_entry)
b1.pack(side=tk.LEFT)
b2.pack(side=tk.LEFT)
b3.pack(side=tk.LEFT)
b4.pack(side=tk.LEFT)
frame3 = tk.Frame(self.parent) # select of names
frame3.pack()
scroll = tk.Scrollbar(frame3, orient=tk.VERTICAL)
self.select = tk.Listbox(frame3, yscrollcommand=scroll.set, height=6)
scroll.config(command=self.select.yview)
scroll.pack(side=tk.RIGHT, fill=tk.Y)
self.select.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
def set_select(self):
user_list.sort()
self.select.delete(0, tk.END)
for name in user_list:
self.select.insert(tk.END, name)
if __name__ == '__main__':
root = tk.Tk()
Domain(root)
root.mainloop()
Note:
There's still errors here, but I don't exactly know what you're trying to do so I've just restructured it here so you can start on a better path.