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
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()
Full error description:
Traceback (most recent call last):
File "C:\Технології\Лабораторки\ЛР 25\ЛР25.py", line 484, in
app = App()
File "C:\Технології\Лабораторки\ЛР 25\ЛР25.py", line 49, in init
self.createMainMenu()
File "C:\Технології\Лабораторки\ЛР 25\ЛР25.py", line 63, in createMainMenu
thememenu = tk.Menu(self.submenus[1], bg = "black", selectcolor = "white", fg = "white", activebackground = "white", activeforeground = "black", tearoff = 0)
File "C:\Users\bredu\AppData\Local\Programs\Python\Python311\Lib\tkinter_init_.py", line 3343, in init
Widget.init(self, master, 'menu', cnf, kw)
File "C:\Users\bredu\AppData\Local\Programs\Python\Python311\Lib\tkinter_init_.py", line 2628, in init
self.tk.call(
_tkinter.TclError: can't invoke "menu" command: application has been destroyed
My app:
I'm trying to make a menu.
Code:
import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageTk
import webbrowser
class App(tk.Tk):
topbuttons = None
service = None
openAnimeListButton = None
childWindow = None
hint = None
frames = None
mainmenu = None
submenus = []
def __init__(self):
super().__init__()
self.title("Мои самые любимые аниме-тайтлы")
self.protocol("WM_DELETE_WINDOW", self.on_closing)
self.geometry("1200x680")
self.resizable(False, False)
self["background"] = "black"
self.frames = [tk.Frame(self), tk.LabelFrame(self, text = "Сколько вам лет?", font = "Arial 13", bg = "black", fg = "white")]
bt1 = tk.Button(self.frames[0], text = "Сёнэн", height = 2, width = 14, bg = "black", fg = "white",\
font = "Arial 13", relief = "groove", overrelief = "sunken")
bt2 = tk.Button(self.frames[0], text = "Комедия", height = 2, width = 14, bg = "black", fg = "white",\
font = "Arial 13", relief = "groove", overrelief = "sunken")
bt3 = tk.Button(self.frames[0], text = "Психология", height = 2, width = 14, bg = "black", fg = "white",\
font = "Arial 13", relief = "groove", overrelief = "sunken")
bt4 = tk.Button(self.frames[0], text = "Повседневность", height = 2, width = 16, bg = "black", fg = "white",\
font = "Arial 13", relief = "groove", overrelief = "sunken")
bt5 = tk.Button(self.frames[0], text = "Триллер", height = 2, width = 14, bg = "black", fg = "white",\
font = "Arial 13", relief = "groove", overrelief = "sunken")
self.topbuttons = [bt1, bt2, bt3, bt4, bt5]
self.frames[0].pack()
for x in self.topbuttons:
x.pack(side="left")
self.openAnimeListButton = tk.Button(self, text = "Открыть список\nпросмотренных мною аниме", height = 2, width = 26, bg = "black", fg = "white",\
font = "Arial 13", relief = "groove", overrelief = "sunken")
self.openAnimeListButton.place(x = 956, y = 628)
self.service = Service(self)
self.hint = tk.Label(self, text = "Ctrl+Double click the left mouse\nbutton - close app.\nCtrl+Shift+R - restart app.\nCtrl+o - open child window.", justify = "left", bg = "black", fg = "white", font = "Arial 18", cursor="hand2")
self.hint.place(x = 1, y = 565)
self.createMainMenu()
def createMainMenu(self):
self.mainmenu = tk.Menu(self)
self.config(menu=self.mainmenu)
self.mainmenu.add_command(label="Аниме")
animemenu = tk.Menu(self.mainmenu, bg = "black", fg = "white", activebackground = "white", activeforeground = "black", tearoff = 0)
viewmenu = tk.Menu(self.mainmenu, bg = "black", fg = "white", activebackground = "white", activeforeground = "black", tearoff = 0)
docmenu = tk.Menu(self.mainmenu, bg = "black", fg = "white", activebackground = "white", activeforeground = "black", tearoff = 0)
self.submenus.append(animemenu)
self.submenus.append(viewmenu)
self.submenus.append(docmenu)
self.mainmenu.add_cascade(label = "Вид", menu = self.submenus[1])
thememenu = tk.Menu(self.submenus[1], bg = "black", selectcolor = "white", fg = "white", activebackground = "white", activeforeground = "black", tearoff = 0) #Here's an error
self.submenus.append(thememenu)
optionVar = tk.BooleanVar()
optionVar.set(0)
self.submenus[3].add_radiobutton(label = "Тёмная", value=0, variable=optionVar, command = self.service.makeBlackTheme)
self.submenus[3].add_radiobutton(label = "Светлая", value=1, variable=optionVar, command = self.service.makeLightTheme)
self.submenus[1].add_cascade(label = "Тема", menu = self.submenus[3])
self.mainmenu.add_cascade(label = "Справка", menu = self.submenus[2])
self.submenus[2].add_command(label = "О приложении", command = self.service.showInfoAboutApp)
self.submenus[2].add_command(label = "Контакт. данные разраба", command = self.service.showContact)
def startApp(self):
print("Начало программы.")
self.mainloop()
print("Конец программы.")
def on_closing(self):
if messagebox.askokcancel("Выход из приложения", "Хотите выйти из приложения?"):
global running
running = False
self.delObject()
def delObject(self):
for x in self.topbuttons:
del x
del self.service
del self.openAnimeListButton
if self.childWindow != None: del self.childWindow
del self.hint
for x in self.frames:
del x
for x in self.submenus:
del x
del self.mainmenu
self.destroy()
class Service():
root = None
showedElementsByClickingButtom = {}
activeElements = None
checker = False
links = {}
activeLinks = None
clickedButton = None
printedAge = None
constantAge = None
checkbutton = None
myTextField = None
mySendAgeButton = None
ageLabel = None
myRadioButtons = None
listOfAnimesElement = None
listOfAnimes = None
listOfAnimes_var = None
currentButtonIndex = 0
wasCurrentButtonIndexLastChangedAfterTab = False
windowInfoAboutApp = None
windowContactInfo = None
lbContactInfoOrInAboutApp = None
def __init__(self, root):
self.root = root
for btn in self.root.topbuttons:
btn.config(command = lambda text = btn["text"]: self.printInfoAboutAnime(text))
btn.bind("<Enter>", lambda event, bt = btn: self.showPage(event, bt))
self.root.bind('<Control-Double-Button-1>', self.exitWin)
self.root.bind('<Control-Shift-R>', self.restartApp)
self.root.bind('<Control-o>', self.openChildWindow)
self.root.openAnimeListButton.bind('<Button-3>', lambda event, btn = self.root.openAnimeListButton: self.changeStyleOfButton(event, btn))
self.root.openAnimeListButton.bind('<Button-1>', self.openChildWindow)
def exitWin(self, event):
self.root.on_closing()
def restartApp(self, event):
print("Перезапуск программы.")
self.delObject()
self.root.delObject()
def delObject(self):
allGenres = list(self.showedElementsByClickingButtom.keys())
if allGenres != None:
for x in allGenres:
del self.showedElementsByClickingButtom[x]
def makeBlackTheme(self):
print("Black")
def makeLightTheme(self):
print("Light")
def changeStyleOfButton(self, event, btn):
btn.config(bg = "green", fg = "red", activebackground = "black", activeforeground = "green")
def showPage(self, event, btn):
btn.invoke()
def showInfoAboutApp(self):
if self.windowInfoAboutApp != None:
self.windowInfoAboutApp.destroy()
if self.windowContactInfo != None:
self.windowContactInfo.destroy()
if self.root.childWindow != None:
self.root.childWindow.destroy()
self.windowInfoAboutApp = tk.Toplevel(self.root, highlightthickness = 0, bd = 0)
self.windowInfoAboutApp.title("Информация о приложении")
self.windowInfoAboutApp.resizable(False, False)
self.windowInfoAboutApp["background"] = "black"
self.windowInfoAboutApp.geometry("450x215+600+300")
self.lbContactInfoOrInAboutApp = tk.Label(self.windowInfoAboutApp, justify = "left", text = "Данное приложение было создано с целью \nпоказать мои навыки разработки графического \nинтерфейса пользователя, используя объектно-\nориентированный подход. В приложении вы \nсможете увидеть по два моих самых любимых \nаниме из 5 самых любимых жанров, список \nпросмотренных аниме, а также вы сможете \nпройти небольшой опросик) \nЖелаю удачи!;)", bg = "black", fg = "white", font = "Arial 14")
self.lbContactInfoOrInAboutApp.place(x = 1, y = 1)
def showContact(self):
if self.windowInfoAboutApp != None:
self.windowInfoAboutApp.destroy()
if self.windowContactInfo != None:
self.windowContactInfo.destroy()
if self.root.childWindow != None:
self.root.childWindow.destroy()
self.windowContactInfo = tk.Toplevel(self.root, highlightthickness = 0, bd = 0)
self.windowContactInfo.title("Контактная информация разработчика")
self.windowContactInfo.resizable(False, False)
self.windowContactInfo["background"] = "black"
self.windowContactInfo.geometry("275x120+600+300")
self.lbContactInfoOrInAboutApp = tk.Label(self.windowContactInfo, justify = "left", text = "ФИО:\nБредун Денис Сергеевич\nНомера телефонов:\n0636515388 - Telegram, Viber\n0995354808 - Telegram", bg = "black", fg = "white", font = "Arial 14")
self.lbContactInfoOrInAboutApp.place(x = 1, y = 1)
def openChildWindow(self, event):
if self.windowInfoAboutApp != None:
self.windowInfoAboutApp.destroy()
if self.windowContactInfo != None:
self.windowContactInfo.destroy()
if self.root.childWindow != None:
self.root.childWindow.destroy()
self.root.childWindow = tk.Toplevel(self.root, highlightthickness = 0, bd = 0)
self.root.childWindow.title("Список просмотренных мною аниме")
self.root.childWindow.resizable(False, False)
self.root.childWindow["background"] = "black"
self.listOfAnimes = ["Город, в котором меня нет", "Эхо террора", "Приоритет Чудо-Яйца", "Берсерк", "Союз серокрылых", "Нет игры - нет жизни", "Мастера меча онлайн", "Тетрадь смерти", "Фальшивая любовь", "Врата Штейна (все сезоны)", "Цикл историй", "Удзаки хочет тусоваться!", "Ушастые друзья", "Oregairu", "Моя заботливая 800-летняя жена", "Песнь ночных сов", "Вайолет Эвергарден", "Человек-бензопила", "Добро пожаловать в класс превосходства", "Призрак в доспехах"]
self.listOfAnimes_var = tk.Variable(value=self.listOfAnimes)
self.listOfAnimesElement = tk.Listbox(self.root.childWindow, listvariable = self.listOfAnimes_var, font = "Arial 16", bg = "black", fg = "white", selectbackground = "white", selectmode = "single", selectforeground = "red")
self.root.childWindow.geometry("450x255+600+300")
self.listOfAnimesElement.pack(fill="x")
scroll = tk.Scrollbar(self.listOfAnimesElement, command=self.listOfAnimesElement.yview)
scroll.place(x = 430, height = 250)
self.listOfAnimesElement.config(yscrollcommand=scroll.set)
def callback(self, url):
webbrowser.open_new(url)
def on_checked(self, cvar):
if cvar.get() == 1:
self.checker = True
if len(self.links) == 0:
lb1 = tk.Label(self.root, text = "Описание", bg = "black", fg = "cyan", font = "Arial 18", cursor="hand2")
lb1.bind("<Button-1>", lambda e: self.callback("https://jut-su.net/91-van-pis-f1.html"))
lb2 = tk.Label(self.root, text = "Описание", bg = "black", fg = "cyan", font = "Arial 18", cursor="hand2")
lb2.bind("<Button-1>", lambda e: self.callback("https://jut-su.net/45-moja-gerojskaja-akademija.html"))
lb3 = tk.Label(self.root, text = "Описание", bg = "black", fg = "cyan", font = "Arial 18", cursor="hand2")
lb3.bind("<Button-1>", lambda e: self.callback("https://jut-su.net/231-jetot-zamechatelnyj-mir-s1.html"))
lb4 = tk.Label(self.root, text = "Описание", bg = "black", fg = "cyan", font = "Arial 18", cursor="hand2")
lb4.bind("<Button-1>", lambda e: self.callback("https://jut-su.net/454-neobjatnyj-okean.html"))
lb5 = tk.Label(self.root, text = "Описание", bg = "black", fg = "cyan", font = "Arial 18", cursor="hand2")
lb5.bind("<Button-1>", lambda e: self.callback("https://jut-su.net/1185-moja-devushka-sovsem-ne-milaja-y1.html"))
lb6 = tk.Label(self.root, text = "Описание", bg = "black", fg = "cyan", font = "Arial 18", cursor="hand2")
lb6.bind("<Button-1>", lambda e: self.callback("https://jut-su.net/124-udzaki-hochet-tusovatsja.html"))
lb7 = tk.Label(self.root, text = "Описание", bg = "black", fg = "cyan", font = "Arial 18", cursor="hand2")
lb7.bind("<Button-1>", lambda e: self.callback("https://jut-su.net/724-dobro-pozhalovat-v-klass-prevoshodstva.html"))
lb8 = tk.Label(self.root, text = "Описание", bg = "black", fg = "cyan", font = "Arial 18", cursor="hand2")
lb8.bind("<Button-1>", lambda e: self.callback("https://jut-su.net/99-obeschannyj-neverlend.html"))
lb9 = tk.Label(self.root, text = "Описание", bg = "black", fg = "cyan", font = "Arial 18", cursor="hand2")
lb9.bind("<Button-1>", lambda e: self.callback("https://jut-su.net/1069-prioritet-chudo-jajca.html"))
lb10 = tk.Label(self.root, text = "Описание", bg = "black", fg = "cyan", font = "Arial 18", cursor="hand2")
lb10.bind("<Button-1>", lambda e: self.callback("https://jut-su.net/1026-jeho-terrora.html"))
self.links = {
"Сёнэн": [lb1, lb2],
"Комедия": [lb3, lb4],
"Повседневность": [lb5, lb6],
"Психология": [lb7, lb8],
"Триллер": [lb9, lb10]
}
self.showLinksOnThePage()
else:
self.checker = False
self.deleteActiveLinks()
def showLinksOnThePage(self):
if self.clickedButton == "Сёнэн":
self.links[self.clickedButton][0].place(x = 150, y = 410)
self.links[self.clickedButton][1].place(x = 885, y = 480)
elif self.clickedButton == "Комедия":
self.links[self.clickedButton][0].place(x = 140, y = 315)
self.links[self.clickedButton][1].place(x = 840, y = 315)
elif self.clickedButton == "Повседневность":
self.links[self.clickedButton][0].place(x = 185, y = 460)
self.links[self.clickedButton][1].place(x = 870, y = 480)
elif self.clickedButton == "Психология":
self.links[self.clickedButton][0].place(x = 160, y = 480)
self.links[self.clickedButton][1].place(x = 850, y = 420)
else:
self.links[self.clickedButton][0].place(x = 170, y = 480)
self.links[self.clickedButton][1].place(x = 863, y = 470)
self.activeLinks = self.links[self.clickedButton]
def deleteActiveLinks(self):
for x in self.activeLinks:
x.place(x = 9999999, y = 9999999)
def is_valid(self, newval):
return newval == "" or (newval != " " and newval.isdigit() and len(newval) <= 100 and int(newval) <= 100 and int(newval) > 0)
def printDependingOnAge(self):
if self.constantAge == None:
if self.printedAge.get().isdigit():
age = int(self.printedAge.get())
if self.ageLabel != None:
self.ageLabel.place(x = 9999999, y = 9999999)
else:
self.ageLabel = tk.Label(self.root, text = "Введите возраст!!!", font = "Arial 13", bg = "black", fg = "white")
self.ageLabel.place(x = 490, y = 240)
return 0
if age <= 7:
self.ageLabel = tk.Label(self.root, text = "Тебе мало лет для подобного рода аниме.", font = "Arial 13", bg = "black", fg = "white")
self.ageLabel.place(x = 400, y = 240)
elif age >= 75:
self.ageLabel = tk.Label(self.root, text = "Здоровья вам!=)", font = "Arial 13", bg = "black", fg = "white")
self.ageLabel.place(x = 480, y = 240)
else:
self.ageLabel = tk.Label(self.root, text = 'Смотрели аниме "Берсерк"?', font = "Arial 13", bg = "black", fg = "white")
self.ageLabel.place(x = 450, y = 240)
r_var = tk.IntVar()
r_var.set(0)
r1 = tk.Radiobutton(self.root, font = "Arial 13", disabledforeground = "green", text='Да', command = lambda r_var = r_var: self.checkIfUserWatchedBerserk(r_var), variable=r_var, value=1, activeforeground = "green", activebackground = "black", bg = "black", fg = "green")
r2 = tk.Radiobutton(self.root, font = "Arial 13", disabledforeground = "red", text='Нет', command = lambda r_var = r_var: self.checkIfUserWatchedBerserk(r_var), variable=r_var, value=2, activeforeground = "red", activebackground = "black", bg = "black", fg = "red")
r1.place(x = 510, y = 270)
r2.place(x = 570, y = 270)
self.myRadioButtons = [r1, r2]
self.constantAge = int(self.printedAge.get())
def checkIfUserWatchedBerserk(self, r_var):
answer = int(r_var.get())
if answer == 1:
im = Image.open("dicaprio.png")
kh = im.height/350
im = im.resize((round(im.width/kh), round(im.height/kh)), Image.Resampling.LANCZOS)
im = ImageTk.PhotoImage(im)
lb = tk.Label(self.root, image = im, bd = 0)
lb.image = im
lb.place(x = 400, y = 320)
elif answer == 2:
im = Image.open("bladerunner.png")
kh = im.width/350
im = im.resize((round(im.width/kh), round(im.height/kh)), Image.Resampling.LANCZOS)
im = ImageTk.PhotoImage(im)
lb = tk.Label(self.root, image = im, bd = 0)
lb.image = im
lb.place(x = 400, y = 320)
self.myRadioButtons[0]["state"] = "disabled"
self.myRadioButtons[1]["state"] = "disabled"
def sendDataAboutAge(self, event):
self.mySendAgeButton.invoke()
def printInfoAboutAnime(self, text):
self.clickedButton = text
if self.checkbutton == None:
cvar = tk.IntVar()
cvar.set(0)
self.checkbutton = tk.Checkbutton(self.root, activeforeground = "green", activebackground = "black", bg = "black", fg = "green", text="Ссылки на описания", variable=cvar, command = lambda cvar = cvar: self.on_checked(cvar), font = "Arial 18")
self.checkbutton.place(x = 430, y = 140)
self.printedAge = tk.StringVar()
check = (self.root.register(self.is_valid), "%P")
self.myTextField = tk.Entry(self.root.frames[1], width=3, validate="key", validatecommand=check, textvariable = self.printedAge, highlightthickness = 0, bd = 0, font = "Arial 15")
self.myTextField.bind('<Return>', self.sendDataAboutAge)
self.myTextField.pack(side="left")
self.mySendAgeButton = tk.Button(self.root.frames[1], text = "Отправить", height = 1, width = 16, bg = "black", fg = "white",\
font = "Arial 10", relief = "groove", overrelief = "sunken", command = self.printDependingOnAge)
self.mySendAgeButton.pack(side="left")
self.root.frames[1].place(x = 480, y = 180)
if self.checker == True:
self.deleteActiveLinks()
self.showLinksOnThePage()
self.chooseWhat2LabelsToPrint(text)
self.chooseWhat2ImagesToPrint(text)
def chooseWhat2LabelsToPrint(self, text):
if len(self.showedElementsByClickingButtom) == 0:
self.print2Labels(text)
else:
for x in self.activeElements["labels"]:
x.place(x = 9999999, y = 999999)
try:
for x in self.activeElements["images"]:
x.place(x = 9999999, y = 999999)
except:
pass
allGenres = list(self.showedElementsByClickingButtom.keys())
for x in allGenres:
if x == text:
if text == "Сёнэн":
self.showedElementsByClickingButtom[text]["labels"][0].place(x = 175, y = 75)
self.showedElementsByClickingButtom[text]["labels"][1].place(x = 800, y = 75)
elif text == "Комедия":
self.showedElementsByClickingButtom[text]["labels"][0].place(x = 150, y = 75)
self.showedElementsByClickingButtom[text]["labels"][1].place(x = 800, y = 75)
elif text == "Повседневность":
self.showedElementsByClickingButtom[text]["labels"][0].place(x = 75, y = 75)
self.showedElementsByClickingButtom[text]["labels"][1].place(x = 783, y = 75)
elif text == "Психология":
self.showedElementsByClickingButtom[text]["labels"][0].place(x = 0, y = 75)
self.showedElementsByClickingButtom[text]["labels"][1].place(x = 765, y = 75)
else:
self.showedElementsByClickingButtom[text]["labels"][0].place(x = 110, y = 75)
self.showedElementsByClickingButtom[text]["labels"][1].place(x = 845, y = 75)
self.activeElements = self.showedElementsByClickingButtom[text]
return 0
self.print2Labels(text)
def print2Labels(self, text):
if text == "Сёнэн":
text1 = "Ван Пис"
text2 = "Моя геройская академия"
lb1 = tk.Label(self.root, text = text1, bg = "black", fg = "white", font = "Arial 18")
lb2 = tk.Label(self.root, text = text2, bg = "black", fg = "white", font = "Arial 18")
lb1.place(x = 175, y = 75)
lb2.place(x = 800, y = 75)
elif text == "Комедия":
text1 = "Коносуба"
text2 = "Необъятый океан"
lb1 = tk.Label(self.root, text = text1, bg = "black", fg = "white", font = "Arial 18")
lb2 = tk.Label(self.root, text = text2, bg = "black", fg = "white", font = "Arial 18")
lb1.place(x = 150, y = 75)
lb2.place(x = 800, y = 75)
elif text == "Повседневность":
text1 = "Моя девушка не только милая"
text2 = "Удзаки хочет тусоваться!"
lb1 = tk.Label(self.root, text = text1, bg = "black", fg = "white", font = "Arial 18")
lb2 = tk.Label(self.root, text = text2, bg = "black", fg = "white", font = "Arial 18")
lb1.place(x = 75, y = 75)
lb2.place(x = 783, y = 75)
elif text == "Психология":
text1 = "Добро пожаловать в класс превосходства"
text2 = "Обещанный Неверленд"
lb1 = tk.Label(self.root, text = text1, bg = "black", fg = "white", font = "Arial 18")
lb2 = tk.Label(self.root, text = text2, bg = "black", fg = "white", font = "Arial 18")
lb1.place(x = 0, y = 75)
lb2.place(x = 765, y = 75)
else:
text1 = "Приоритет Чудо-Яйца"
text2 = "Эхо Террора"
lb1 = tk.Label(self.root, text = text1, bg = "black", fg = "white", font = "Arial 18")
lb2 = tk.Label(self.root, text = text2, bg = "black", fg = "white", font = "Arial 18")
lb1.place(x = 110, y = 75)
lb2.place(x = 845, y = 75)
self.showedElementsByClickingButtom.update({text:{"labels": [lb1, lb2]}})
self.activeElements = self.showedElementsByClickingButtom[text]
def chooseWhat2ImagesToPrint(self, text):
if text == "Сёнэн":
file1 = "Сёнэн/One_Piece.png"
file2 = "Сёнэн/My_Hero_Academia.png"
elif text == "Комедия":
file1 = "Комедия/Konosuba.png"
file2 = "Комедия/grand_blue.png"
elif text == "Повседневность":
file1 = "Повседневность/cute.png"
file2 = "Повседневность/Udzaki.png"
elif text == "Психология":
file1 = "Психология/class.png"
file2 = "Психология/promised_neverland.png"
else:
file1 = "Триллер/wondereggpriority.png"
file2 = "Триллер/Zankyou_no_Terror.png"
try:
allGenres = list(self.showedElementsByClickingButtom.keys())
for x in allGenres:
if x == text:
self.showedElementsByClickingButtom[text]["images"][0].place(x = 110, y = 120)
self.showedElementsByClickingButtom[text]["images"][1].place(x = 800, y = 120)
self.activeElements = self.showedElementsByClickingButtom[text]
return 0
except:
self.print2Images(text, file1, file2, 110, 120, 800, 120)
def print2Images(self, text, file1, file2, x1, y1, x2, y2):
image1 = Image.open(file1)
if image1.height > 350:
kh = image1.height/350
image1 = image1.resize((round(image1.width/kh), round(image1.height/kh)), Image.Resampling.LANCZOS)
image2 = Image.open(file2)
if image2.height > 350:
kh = image2.height/350
image2 = image2.resize((round(image2.width/kh), round(image2.height/kh)), Image.Resampling.LANCZOS)
image1 = ImageTk.PhotoImage(image1)
image2 = ImageTk.PhotoImage(image2)
lb1 = tk.Label(self.root, image = image1, bd = 0)
lb2 = tk.Label(self.root, image = image2, bd = 0)
lb1.image = image1
lb2.image = image2
lb1.place(x = x1, y = y1)
lb2.place(x = x2, y = y2)
allGenres = list(self.showedElementsByClickingButtom.keys())
for x in allGenres:
if x == text:
self.showedElementsByClickingButtom[text].update({"images":[lb1, lb2]})
self.activeElements = self.showedElementsByClickingButtom[text]
return 0
self.showedElementsByClickingButtom.update({text:{"images": [lb1, lb2]}})
self.activeElements = self.showedElementsByClickingButtom[text]
running = True
if __name__ == "__main__":
while running:
app = App()
app.startApp()
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)