Python GUI tkinter - solve secondary loop - python

I m beginner in Python. Exist any possible way, how to loop in def and return to mainloop after user make some reaction, like click button?
In code down: Mainloop jump to def work, next to def start. After click button Start change the Buttons and after click on it, return to mainloop. So command "print ("App comes here...")" execute after clicking new button...
Thx a lot for any clue.
from tkinter import *
win_dow=Tk()
win_dow.geometry("600x300")
def work():
def start():
"Here somehow loop"
line_2_r2.remove(btn_start)
line_2_r2.add(btn_back)
def back():
"""
Here return to mainloop...
"""
line_2_r2.remove(btn_back)
line_2_r2.add(btn_start)
pan_win = PanedWindow(win_dow, borderwidth = 0, bg = "black", width = 600, height = 300, orient=VERTICAL)
pan_win.pack()
line_1 = PanedWindow(pan_win, borderwidth = 0, bg = "blue", width = 600, height = 100, orient=HORIZONTAL)
pan_win.add(line_1)
line_2 = PanedWindow(pan_win, borderwidth = 0, bg = "black", width = 600, height = 100, orient=HORIZONTAL)
pan_win.add(line_2)
line_2_r1 = PanedWindow(line_2, borderwidth = 0, bg = "yellow", width = 200, height = 100, orient=VERTICAL)
line_2.add(line_2_r1)
line_2_r2 = PanedWindow(line_2, borderwidth = 0, bg = "orange", width = 200, height = 100, orient=VERTICAL)
line_2.add(line_2_r2)
line_2_r3 = PanedWindow(line_2, borderwidth = 0, bg = "purple", width = 200, height = 100, orient=VERTICAL)
line_2.add(line_2_r3)
line_3 = PanedWindow(pan_win, borderwidth = 0, bg = "green", width = 600, height = 100, orient=HORIZONTAL)
pan_win.add(line_3)
btn_start = Button(line_2_r2, text= "Start", font="Arial, 12", command=start)
line_2_r2.add(btn_start)
btn_back = Button(line_2_r2, text= "Go back", font="Arial, 12", command=back)
work()
print ("App comes here...")
win_dow.mainloop()

Related

How to give a value in function to another function

In my app, settings button are initiating a window, in that window you insert your link and this link need to get back to main function and work with button, which open this link in browser
from tkinter import *
from tkinter import messagebox
def validate(P):
if len(P) == 0:
return True
elif len(P) <= 10:
return True
else:
return False
def validate_en(s):
pass
def close():
if messagebox.askokcancel("Close window", "Are u sure you want to exit?"):
web.destroy()
if __name__ == "__main__":
web = Tk()
web.configure(background = "black")
web.title("WebSaver")
web.geometry("600x400")
web.iconbitmap('icon.ico')
web.resizable(False, False)
web.protocol("WM_DELETE_WINDOW", close)
def main_content():
web.withdraw()
main = Toplevel(web)
main.title("Application")
main.geometry("800x600")
main.iconbitmap('icon.ico')
main.protocol("WM_DELETE_WINDOW", close)
main.resizable(False, False)
canvas = Canvas(main,width = "800", height = "600", highlightthickness = 0, bg =
"black")
canvas.pack(fill = BOTH, expand = True)
upper_text = Label(canvas, text= "TEXT", justify = "center", background =
"black", foreground = "white", font = "KacstDigital, 20", borderwidth = 2,
highlightthickness = 1, highlightbackground = "gray")
upper_text.pack(padx = 5)
def link_1():
pass
button_1 = Button(canvas, text = "First link", bg = "#293133", fg = "white", font
= "KacstDigital, 18", height = 2, width = 15, command = lambda: link_1)
button_1.place(x = 30, y = 150)
button_conf_1 = Button(canvas, text = "settings", bg = "#293133", fg = "white",
font = "KacstDigital, 7", width = 7, command = configurate_button_1)
button_conf_1.place(x = 198, y = 203)
def configurate_button_1():
def close():
conf.destroy()
def apply(link):
if (link.isspace() or link == ""):
messagebox.showwarning(title = "Error!", message = "Input is null")
else:
close()
return link
conf = Toplevel(web)
conf.title("Application")
conf.geometry("600x100")
conf.iconbitmap('icon.ico')
conf.protocol("WM_DELETE_WINDOW", close)
conf.resizable(False, False)
canvas = Canvas(conf, width = "600", height = "100", highlightthickness = 0, bg =
"black")
canvas.pack(fill = BOTH, expand = True)
vcmd = (canvas.register(validate_en), '%s')
link_text = Label(canvas, text= "Link: ", justify = "center", background =
"black", foreground = "white", font = "KacstDigital, 12", borderwidth = 2,
highlightthickness = 1, highlightbackground = "gray")
link_text.place(x = 5, y = 10)
link_entry = Entry(canvas, bg = "#293133", fg = "white", font = "KacstDigital,
14", width = 45, validate = "key", validatecommand = vcmd)
link_entry.place(x = 78, y = 10)
link_button = Button(canvas, text = "Confirm changes", bg = "#293133", fg =
"white", font = "KacstDigital, 14", height = 1, width = 20, command = lambda:
apply(link_entry.get()))
link_button.place(x = 15, y = 50)
main_content()
web.mainloop()
I need help with getting value from link_entry (in conf.button func.) and give this value to main_content to open this link from main_content.
Sorry for this strange option strings, idk how to get them at the right place

How can I run python script inside a frame in tkinter?

I have a function that asks the user to answer a couple of question which prints out a result I have written my code inside a function called Script and I made it so when I press a button the function runs but in my terminal while I want it to run inside the frame I created
Here is my code:
from tkinter import *
def Script():
#My script/code is written here
root = tk.Tk()
root.configure(background = "#110a60")
canvas = tk.Canvas(root, height = 750, width = 800, bg = "#110a60")
canvas.pack()
root.resizable(False, False)
frame = tk.Frame(root, bg = "black")
frame.place(relheight = 0.8, relwidth = 0.8, relx = 0.1, rely = 0.1)
start_button = Button(root, text = 'Start Program', padx = 10, pady = 5, fg = "#FFFF00", bg = "#012456", command = Script)
start_button.place(x = 350, y = 680)
exit_button = Button(root, text = 'Exit', padx = 20, pady = 5, fg = "#FFFF00", bg = "#012456", command = exit)
exit_button.place(x = 368, y = 714.5 )
root.mainloop()
So how can I make it when I press the Start program button the text and input outputting to the terminal/console be printed inside the frame I made(inside the red borders)
And Thanks in advance
Simple answer: You can't. print() is for the console.
More elaborate answer:
You'll probably need a Label() widget for your questions and a Entry() widget for user input. Also your script() function should not print but return a string which you can then display in a Text() widget.
Edit (added some code to your code to get you going):
from tkinter import Tk, Canvas, Frame, Button, Label, Entry, StringVar, Text
def my_script():
questions=["What is your name?",
"What is your age?"]
answers = []
answer_box.config(background='grey')
answer_box.focus()
for question in questions:
question_label.config(text=question)
answer_box.wait_variable(answer_given)
answers.append(answer_box.get())
answer_box.delete(0, 'end')
answer_box.focus()
for answer in answers:
print_area.insert('end', answer+"\n")
root = Tk()
root.configure(background = "#110a60")
canvas = Canvas(root, height = 750, width = 800, bg = "#110a60")
canvas.pack()
root.resizable(False, False)
frame = Frame(root, bg = "black")
frame.place(relheight = 0.8, relwidth = 0.8, relx = 0.1, rely = 0.1)
start_button = Button(root, text = 'Start Program', padx = 10, pady = 5, fg = "#FFFF00", bg = "#012456", command = my_script)
start_button.place(x = 350, y = 680)
exit_button = Button(root, text = 'Exit', padx = 20, pady = 5, fg = "#FFFF00", bg = "#012456", command = exit)
exit_button.place(x = 368, y = 714.5 )
question_label = Label(frame, text="", bg='black', fg='white')
question_label.place(relx=0.5, y=80, anchor='center')
answer_given = StringVar()
answer_box = Entry(frame, bg='black', borderwidth=0)
answer_box.place(relx=0.5, y=110, anchor='center')
answer_box.bind('<Return>', lambda x: answer_given.set("foobar"))
print_area = Text(frame, bg='black', fg='white')
print_area.place(relx=0.5, y=180, height=300, width=500, anchor='n')
root.mainloop()

Why do the tkinter windows open when the program runs and not when the buttons are pressed?

I am trying to code a journal using tkinter. I have used different scripts for each part of the journal (main menu, morning entry and evening entry). I have set it so that the windows for morning and evening entry only open when their respective buttons are pressed on the main menu and this works well but when I run the programs both windows open automatically without me pressing anything. This happens before the main menu window is even opened. I have checked through the code and not noticed anything that can be causing this. Below is my code for the main menu and for the morning menu (evening is the same as morning menu with variables changed).
Main Menu
#importing libraries
import tkinter as tk
from tkinter import *
from Morning import *
from Evening import *
def StartUp():
Start = tk.Tk()
#Start Window Title and Size
Start.title("Journal")
Start.geometry("600x500")
Start["bg"] = "white"
#header Box
header = Label(Start, text = "Journal",
height = 1,
width = 7,
font = ("Comic Sans", 16, "bold"),
bg = "white")
header.pack(side = TOP)
#Buttons
morning_button = Button(Start, height = 2,
width = 20,
text = "Morning",
bg = "white",
command = lambda : morningwindow(),
)
morning_button.pack(side = LEFT)
evening_button = Button(Start, height = 2,
width = 20,
text = "Evening",
bg = "white",
command = lambda : eveningwindow())
evening_button.pack(side = RIGHT)
wklyQs_button = Button(Start, height = 2,
width = 30,
text = "Weekly Questions",
bg = "white")
wklyQs_button.pack()
mnthlycheck_button = Button(Start, height = 2,
width = 30,
text = "Monthly Check In",
bg = "white")
mnthlycheck_button.pack()
quit_button = Button(Start, height = 2,
width = 20,
text = "QUIT",
bg = "white",
command = quit)
quit_button.pack(side = BOTTOM)
#mainloop
Start.mainloop()
StartUp()
Morning Entry
#importing libraries
import tkinter as tk
from tkinter import *
from datetime import *
def morningwindow():
Morning = tk.Tk()
#Morning Window Title and Size
Morning.title("Morning")
Morning.geometry("1400x700")
Morning["bg"] = "#97e8fc"
#header Box
header = Label(Morning, text = "Morning Entry",
height = 1,
width = 20,
font = ("Comic Sans", 16, "bold"),
bg = "white")
header.pack(anchor=N)
#date Box
today = date.today()
format_date = "Today's date", today.strftime("%b-%d-%y")
date_text = Label(Morning, text = (format_date),
height = 1,
width = 20,
font = ("Comic Sans", 16, "bold"),
bg = "white"
)
date_text.pack(anchor=NE, padx = 10, pady = 10)
##Entries
#Grateful Entry
grateful_text = Text(Morning, height = 4, width = 160)
grateful_text.insert(END,
"What are you grateful for? \n1.\n2.\n3.")
grateful_text.pack()
#Good Day Entry
goodday_text = Text(Morning, height = 4, width = 160)
goodday_text.insert(END,
"This is how I'll make today great:")
goodday_text.pack(pady = 10)
#Positive Affirmation Entry
affirm_text = Text(Morning, height = 4, width = 160)
affirm_text.insert(END,
"Positive Affirmation \n")
affirm_text.pack()
##Buttons
#back Button
back_button = Button(Morning, height = 2,
width = 20,
text = "BACK",
bg = "white",
command = lambda : Morning.destroy())
back_button.pack(side = BOTTOM)
#Submit Button
submit_button = Button(Morning, height = 2,
width = 20,
text = "SUBMIT",
bg = "white",
)
submit_button.pack(side = BOTTOM, pady = 10)
#mainloop
Morning.mainloop()

How to get the Scrollbar work during the multiple-entry (with condition) in tkinter frame within the tab?

I was trying to create the scrolled-abled in the frame, where there will be multiple entry lines according to the number of items present. My questions are
1.) My frame Nofy_frame1 with scrollbar is not working (Mentioned the comment #NOT WORKING part) and its position is too close to the entries I did not get any error response. How to solve it?
2.) How to stop/restart the loop while shifting the radio buttons of method 1 and method 2? Since for each click on Add entry button for method 2, the result would be :
Price 1 :
Price 2 :
Price 3 :
Price 4 :
Price 5 :
and then next click on the same Add entry button I am getting
Price 6 :
Price 7 :
Price 8 :
Price 9 :
Price 10 :
instead of the above result
How to resolve it?
I have written the fair code below, Please let me know and clarify my mistakes
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkcalendar import Calendar,DateEntry
from tkinter import messagebox
from tkinter.scrolledtext import ScrolledText
import os
from tkinter import *
import numpy as ny
master0 = tk.Tk()
master0.config(background = "white")
master0.title("Shop Cashier")
master0.geometry("1000x600")
master0.colour_schemes = [{"bg": "#eef1f5", "fg": "black"}, {"bg": "blue", "fg": "white"}]
tabs = ttk.Notebook(master0)
C_1 = 'black'
C_2 = 'white'
TStyler = ttk.Style()
TStyler.configure("TFrame", background=C_2, foreground=C_1, borderwidth=0)
tab1 = ttk.Frame(tabs, style = "TFrame")
tab2 = ttk.Frame(tabs, style = "TFrame")
tab3 = ttk.Frame(tabs, style = "TFrame")
C1 = Canvas(tab1, borderwidth=1, background="white")
C2 = Canvas(tab2, borderwidth=1, background="white")
C2 = Canvas(tab3, borderwidth=1, background="white")
tabs.add(tab1, text ='1')
tabs.add(tab2, text ='2')
tabs.add(tab3, text ='3')
tabs.pack(expand = 1, fill ="both")
#-TAB1
quit_button = tk.Button(tab1, text="Finish", fg="White", bg = "#53c653",padx=10, pady=3,command=master0.destroy)
quit_button.place(x = 450, y= 430)
#-TAB2
InitialInv_r = tk.DoubleVar()
CF_result = tk.DoubleVar()
P_r = tk.DoubleVar()
iiit_r = tk.IntVar()
alent = []
FCI_list = []
VCI_list = []
def addEntry():
if CF_result.get() == 2:
Nofy_frame = Frame(tab2, width = 10, height = 200, bd = 0, background = "#fff080")
Nofy_frame.place(x = 50, y= 150)
Nofy_frame1 = Frame(tab2, width = 270, height = 400, bd = 0, background = "#fff080")
Nofy_frame1.place(x = 50, y= 150)
#============================================================NOT WORKING
Nofy_frame1.pack_propagate(0) # stops frame from shrinking
scroll = Scrollbar(Nofy_frame1)
scroll.pack(side = RIGHT, fill = Y)
#============================================================NOT WORKING
for number in range(iiit_r.get()):
number = len(alent)
#label
ylab = Label(Nofy_frame1, text="Price "+str(number+1)+" :",bg = "#fff080")
ylab.grid(row=number+1, column=0, padx=10, pady=10)
#Entry
ent = Entry(Nofy_frame1, font=('calibri', 11), width = 33)
ent.grid(row=number+1, column=2,padx=10, pady=20)
alent.append( ent )
elif CF_result.get() == 0:
Nofy_frame = Frame(tab2, width = 328, height = 400, bd = 0, background = "#fff080")
Nofy_frame.place(x = 50, y= 150)
Nofy_frame2 = Frame(tab2, width = 270, height = 400, bd = 0, background = "#fff080")
Nofy_frame2.place(x = 50, y= 150)
ylab1 = Label(Nofy_frame2, text="Fixed Price :",bg = "#fff080" )
ylab1.grid(row=1, column=0, padx=2, pady=10)
#Entry
ent = Entry(Nofy_frame2, font=('calibri', 11), width = 30)
ent.grid(row=1, column=2,padx=10, pady=20)
alent.append( ent )
Disct = Label(tab2, text = ' Percentage', bg = "white",padx=3, pady=1,font = ("calibri", 12))
Disct.place(x=400, y=50)
Disctp = Label(tab2, text = '%', bg = "white",padx=3, pady=1,font = ("calibri", 12))
Disctp.place(x=642, y=50)
#Disct_frame = Frame(tab2, width = 200, height = 25, bd = 0, background = "white", highlightcolor = "black", highlightthickness = 1)
#Disct_frame.place(x = 530, y= 50)
Disctv = Entry(tab2,font=('calibri', 12), textvariable= P_r,width = 10, bd=1, bg='#fffce6', justify='left')
Disctv.place(x=560, y=50)
Nofy = Label(tab2, text = 'No. of items :', bg = "white",padx=3, pady=1,font = ("calibri", 12))
Nofy.place(x=700, y=50)
Nofy_frame = Frame(tab2, width = 328, height = 400, bd = 0, background = "#fff080", highlightcolor = "#fff080", highlightthickness = 1)
Nofy_frame.place(x = 50, y= 150)
Nofyv = Entry(tab2,font=('calibri', 12), textvariable= iiit_r, width = 5, bd=1, bg='#fffce6', justify='left')
Nofyv.place(x=800, y=50)
CashFlow = Label(tab2, text = 'Method', bg = "white",padx=3, pady=1,font = ("calibri light", 18))
CashFlow.place(x=50, y=100)
FCF_r = Radiobutton(tab2, variable = CF_result, value = 0, bg = "white")
FCF_r.place(x=180, y=110)
FCF_rr = Label(tab2, text = "method 1", bg = "white",padx=3, pady=1,font = ("calibri light", 12))
FCF_rr.place(x=200, y=108)
vCF_r = Radiobutton(tab2, variable = CF_result, value = 2,bg = "white")
vCF_r.place(x=380, y=110)
vCF_rr = Label(tab2, text = "method 2", bg = "white",padx=3, pady=1,font = ("calibri light", 12))
vCF_rr.place(x=400, y=108)
addEnt = Button(tab2, text='Add entry', fg="White", bg = "#1a1700", command=addEntry)
addEnt.place(x = 400, y= 150)
quit_button = tk.Button(tab2, text="Finish", fg="White", bg = "#53c653",padx=10, pady=3,command=master0.destroy)
quit_button.place(x = 900, y= 530)
master0.mainloop()

TKINTER, images mix when multiple window launched

IMAGE: --->ScreenShot of the problem
IMAGE: --->How it is meant to look:
In the first hyperlink above i have attached a screenshot of the problem.
When running the windows which are connected by a button, the image on the window that is launched from the first window displays on the first window and not on the new window just opened.
At first I thought that python might be getting confused because the file name is the same. (that wasn't the case as I used a slightly different image with a different file name.
I have tried so many ways and it just doesnt work.
Directly below this line is the code for the first window:
#----Main Menu----
root_menu = Tk()
root_menu.title("Warehouse Inventory Control System")
root_menu.configure(bg = "black")
photo = PhotoImage(file="logo.gif")
photoLabel = Label(image=photo)
photoLabel.image = photo
photoLabel.grid(row=1, column=3,columnspan = 4, sticky = N)
Title_Screen = Label(root_menu,
text="Welcome to the SsangYong\n Warehouse Inventory Control System",
fg="grey",
bg="black",
font="Helevetica 25 bold",
pady = "50",
padx = "50",
).grid(row=2, column=3)
Search_Inventory = Button(root_menu,
text = "Search Inventory",
command=Search_Inventory,
fg = "Blue",
bg = "Grey",
bd = 2,
font="Helevetica 12 bold",
height = 1,
width = 50,
).grid(row=16, column=3,pady = 25,padx = 25,)
Add_Stock = Button(root_menu,
text = "Add New Items",
command = Add_To_Database,
fg = "Blue",
bg = "Grey",
bd = 2,
font="Helevetica 12 bold",
height = 1,
width = 60,
).grid(row=15, column=3,pady = 25,padx = 25,)
Print_Report = Button(root_menu,
text = "Print Stock Report",
fg = "Blue",
bg = "Grey",
bd = 2,
font="Helevetica 12 bold",
height = 1,
width = 70,
).grid(row=17, column=3,pady = 25,padx = 25,)
Help_Button = Button(root_menu,
text = "Help",
command=Help_PDF,
fg = "Red",
bg = "Black",
height = "1",
bd = "2",
font = "Helevetica 20 bold",
width = "4",
).grid(row=1, column=3,rowspan = 2, sticky= NE)
root_menu.mainloop()
and here is the code for the second window.
def Search_Inventory():
#---Search Window----
root_search = Tk()
root_search.title("Warehouse Inventory Control System")
root_search.configure(bg = "black")
#----Title displayed under the company logo on the first window----
Title_Screen = Label(root_search,
text="Warehouse Inventory Control System",
fg="grey",
bg="black",
font="Helevetica 25 bold",
pady = "50",
padx = "50",
).grid(row=3, column=4)
#----Interactive Input Boxes for the User----
#----Label to Notify what is needed in the entry box----
PN_Info_Label = Label(root_search,
text = "Part Number:",
fg="white",
bg="black",
font="Helevetica 15 bold",
padx = 50,
).grid(row=14, column=3, rowspan = 2)
#----Input Box for Part Number
PN_Display = StringVar()
Input_PartNumber = Entry(root_search,
textvariable=PN_Display,
fg = "blue",
font = "Helevtica 25 bold",
).grid(row=14, column=4)
#----A button that will proceed to the next part of the program----
Search_Button = Button(root_search,
text = "Search Inventory",
fg = "Blue",
bg = "Grey",
bd = 2,
font="Helevetica 15 bold",
command=lambda:Search_Prod(PN_Display.get()),
height = 1,
width = 15,
).grid(row=16, column=4,pady = 25,padx = 25,)
#----Information regarding how to enter the part number---
Info = Label(root_search,
text="Please Use Capitals to Enter Part Number",
fg= "red",
bg = "black",
font = "helevetica 12 bold",
).grid(row = 15, column = 4)
#----Adding the company logo to the first window----
photo = PhotoImage(file="image.gif")
photoLabel = Label(image=photo)
photoLabel.image = photo
photoLabel.grid(row=1, column=4, pady = 10)
#----Linking the Help Document----
Help_Button = Button(root_search,
text = "Help",
command=Help_PDF,
fg = "Red",
bg = "Black",
height = "1",
bd = "2",
font = "Helevetica 20 bold",
width = "4",
).grid(row=0, column=5, pady= 10,padx = 50, sticky = E)
#----Saying who the program was made by----
Credits = Label(root_search,
text = "Created By: Me",
fg = "White",
bg = "Black",
font = "Helevetica 10 underline",
).grid(row = 19, column = 5)
#To Make Sure that the window doesn't close
root_search.mainloop()
In your question you show this for your "second window":
def Search_Inventory():
#---Search Window----
root_search = Tk()
...
photoLabel = Label(image=photo)
There are two problems with the above code. For one, you're creating a second instance of Tk. You should not do this. A tkinter program should have exactly one instance of Tk. If you want additional windows you need to create instances of Toplevel.
The second problem is where you create the Label -- you are neglecting to give it a parent so it is probably defaulting to the original window. You need to change that last line to this:
photoLabel = Label(root_search, image=photo)

Categories

Resources