How to give a value in function to another function - python

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

Related

Python GUI tkinter - solve secondary loop

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

How to get the status of button in tkinter?

from tkinter import *
import time
def checkTime():
if len(hourInput.get()) != 0 and len(minuteInput.get()) != 0 and len(secondInput.get()) != 0:
if hourInput.get() == time.strftime("%H"):
print("good")
window.after(500, checkTime)
def pressButton(button):
button.config(relief=SUNKEN)
if __name__=='__main__':
window = Tk()
window.geometry("1920x1080")
canvas = Canvas(window, width = 1980, height = 1020)
canvas.pack()
hourInput = StringVar()
minuteInput = StringVar()
secondInput = StringVar()
setHour = Entry(window, text = hourInput, font = (20))
setHour.place(x = 100, y = 20, width = 100, height = 40)
setMinute = Entry(window, text = minuteInput, font = (20))
setMinute.place(x = 300, y = 20, width = 100, height = 40)
setSecond = Entry(window, text = secondInput, font = (20))
setSecond.place(x = 500, y = 20, width = 100, height = 40)
canvas.create_text(60, 40, text = "Hour: ", font = (20))
canvas.create_text(260, 40, text = "Minute: ", font = (20))
canvas.create_text(460, 40, text = "Second: ", font = (20))
submit = Button(text = "Submit", height = 2, width = 10, font = (10))
submit.config(command = lambda submit=submit:pressButton(submit))
submit.place(x = 100, y = 100)
checkTime()
window.mainloop()
I want the function checkTime() to be called when my button is pressed. But how to get the status of my button and compare it ? I want to use the function only if the button is pressed as a test that the user agree with his inputs
You can modify the button declaration as follows so that the checkTime() will trigger when the button is pressed.
submit = Button(text = "Submit", height = 2, width = 10, font = (10), relief=SUNKEN)
submit['command'] = checkTime # no parentheses here
Also make sure that the checkTime() method call in the bottom is removed
I put the function checkTime() inside the pressButton() function, and now the program works fine.
from tkinter import *
import time
def checkTime():
if len(hourInput.get()) != 0 and len(minuteInput.get()) != 0 and len(secondInput.get()) != 0:
if hourInput.get() == time.strftime("%H"):
print("good")
window.after(500, checkTime)
def pressButton(button):
button.config(relief = SUNKEN)
checkTime()
if __name__== '__main__':
window = Tk()
window.geometry("1920x1080")
canvas = Canvas(window, width = 1980, height = 1020)
canvas.pack()
hourInput = StringVar()
minuteInput = StringVar()
secondInput = StringVar()
setHour = Entry(window, text = hourInput, font = (20))
setHour.place(x = 100, y = 20, width = 100, height = 40)
setMinute = Entry(window, text = minuteInput, font = (20))
setMinute.place(x = 300, y = 20, width = 100, height = 40)
setSecond = Entry(window, text = secondInput, font = (20))
setSecond.place(x = 500, y = 20, width = 100, height = 40)
canvas.create_text(60, 40, text = "Hour: ", font = (20))
canvas.create_text(260, 40, text = "Minute: ", font = (20))
canvas.create_text(460, 40, text = "Second: ", font = (20))
submit = Button(text = "Submit", height = 2, width = 10, font = (10))
submit.config(command = lambda submit=submit:pressButton(submit))
submit.place(x = 100, y = 100)
window.mainloop()

Can't modify global variable in python

from tkinter import *
import time
check = False
window = Tk()
window.geometry("1920x1080")
def typeTime():
hour = int(time.strftime("%H"))
minute = int(time.strftime("%M"))
second = int(time.strftime("%S"))
hourInput2 = int(hourInput.get())
minuteInput2 = int(minuteInput.get())
secondInput2 = int(secondInput.get())
if(hour == hourInput2 and minute == minuteInput2 and second == secondInput2):
print("now")
global check
check = True
canvas = Canvas(window, width = 1980, height = 1020)
canvas.pack()
hourInput = StringVar()
minuteInput = StringVar()
secondInput = StringVar()
setHour = Entry(window, text = hourInput, font = (20)).place(x = 100, y = 20, width = 100, height = 40)
setMinute = Entry(window, text = minuteInput, font = (20)).place(x = 300, y = 20, width = 100, height = 40)
setSecond = Entry(window, text = secondInput, font = (20)).place(x = 500, y = 20, width = 100, height = 40)
canvas.create_text(60, 40, text = "Hour: ", font = (20))
canvas.create_text(260, 40, text = "Minute: ", font = (20))
canvas.create_text(460, 40, text = "Second: ", font = (20))
submit = Button(text = "Submit", height = 2, width = 10, font = (10), command = typeTime)
submit.place(x = 100, y = 100)
if check == True:
print("Pressed")
submit.config(relief = SUNKEN)
window.mainloop()
I'm trying to make a button to stay pressed, so I tried to make this happens with a global variable. The variable check is initially False, but when typeTime() is called via the submit object it should change its value in True and when check will be tested later to keep my button pressed using config method.
What am I doing wrong, as neither the button is still pressed nor the message "Pressed" is displayed in the console ?
The window.mainloop() is the internal loop inside object window, not in your script so that is why it didn't work. You need to add the action inside the function typeTime:
from tkinter import *
import time
if __name__=='__main__':
check = False
window = Tk()
window.geometry("1920x1080")
def typeTime(button):
hour = int(time.strftime("%H"))
minute = int(time.strftime("%M"))
second = int(time.strftime("%S"))
hourInput2 = int(hourInput.get())
minuteInput2 = int(minuteInput.get())
secondInput2 = int(secondInput.get())
if(hour == hourInput2 and minute == minuteInput2 and second == secondInput2):
print("now")
# global check
# check = True
print('Pressed')
button.config(relief=SUNKEN)
canvas = Canvas(window, width = 1980, height = 1020)
canvas.pack()
hourInput = StringVar()
minuteInput = StringVar()
secondInput = StringVar()
setHour = Entry(window, text = hourInput, font = (20)).place(x = 100, y = 20, width = 100, height = 40)
setMinute = Entry(window, text = minuteInput, font = (20)).place(x = 300, y = 20, width = 100, height = 40)
setSecond = Entry(window, text = secondInput, font = (20)).place(x = 500, y = 20, width = 100, height = 40)
canvas.create_text(60, 40, text = "Hour: ", font = (20))
canvas.create_text(260, 40, text = "Minute: ", font = (20))
canvas.create_text(460, 40, text = "Second: ", font = (20))
submit = Button(text = "Submit", height = 2, width = 10, font = (10))
submit.config(command = lambda submit=submit:typeTime(submit))
submit.place(x = 100, y = 100)
# if check == True:
# print("Pressed")
# submit.config(relief = SUNKEN)
window.mainloop()

function to open a main GUI using a button from a PopUp GUI

I am new to Python, trying to make the Launch TFL App button open another GUI called "Menu GUI" but I don't know what to do for the def open_Menu(): function below. I want to use the popup GUI below as a launcher which takes the user to my main GUI. The only problem with the code below is that the button for launch TFL app doesn't do anything when you click it.
Here's my current code :
from tkinter import *
root = Tk()
root.title('TFL App')
p = Label(root, text = "TFL Journey Planner", height = "18", width = "250", bg = 'brown', fg =
'white',
font = ('Helvetica', '20', 'bold', 'italic'))
p.pack()
root.configure(bg = 'brown')
root.geometry('400x700')
photo = PhotoImage(file = 'trainstation.png')
label = Label(root, image = photo)
label.pack()
****#Buttons****
def open_Menu():
pass
Button1 = Button(root, text = "Launch TFL App", command = open_Menu, bg = "black", fg = 'white', padx
= 40,
pady = 10,
font = ('Calibri Light', '15', 'bold'))
Button1.pack(padx = 25, pady = 0)
Button2 = Button(root, text = "Exit ", command = root.destroy, bg = "black", fg = 'white', padx = 65,
pady = 8,
font = ('Calibri Light', '15', 'bold'))
Button2.pack(padx = 25, pady = 10)
root.mainloop()
How can I implement open_menu()
The code below is for my Main GUI which should open through the PopUp GUI above but the button on the PopUp GUI is not working.
from tkinter import *
def find():
# get method returns current text
# as a string from text entry box
From = From_field.get()
To = To_field.get()
travel_modes = mode_field.get()
# Calling result() Function
result(From, To, travel_modes)
# Function for inserting the train string
# in the mode_field text entry box
def train():
mode_field.insert(10, "train")
# Function for clearing the contents
def del_From():
From_field.delete(0, END)
distance_field.delete(0, END)
duration_field.delete(0, END)
def del_To():
To_field.delete(0, END)
distance_field.delete(0, END)
duration_field.delete(0, END)
def del_modes():
mode_field.delete(0, END)
distance_field.delete(0, END)
duration_field.delete(0, END)
def delete_all():
From_field.delete(0, END)
To_field.delete(0, END)
mode_field.delete(0, END)
distance_field.delete(0, END)
duration_field.delete(0, END)
# Driver code
if __name__ == "__main__":
# Create a GUI root
root = Tk()
# Set the background colour of GUI root
root.configure(background = 'light blue')
# Set the configuration of GUI root
root.geometry("600x400")
# Created a welcome to distance time calculator label
headlabel = Label(root, text = 'Welcome to your TFL Journey Planner',
fg = 'white', bg = "dark red", height = "0", width = "30",
font = ('calibri light', '19', 'italic'))
# Created a From: label
label1 = Label(root, text = "From:",
fg = 'white', bg = 'black')
# Created a To: label
label2 = Label(root, text = "To:",
fg = 'white', bg = 'black')
# Created a Distance: label
label4 = Label(root, text = "Distance:",
fg = 'white', bg = 'black')
# Created a Duration: label
label5 = Label(root, text = "Duration:",
fg = 'white', bg = 'black')
label6 = Label(root, text = "Choose travelling mode Below: ",
fg = 'white', bg = 'black')
headlabel.grid(row = 0, column = 1)
label1.grid(row = 1, column = 0, sticky = "E")
label2.grid(row = 2, column = 0, sticky = "E")
label4.grid(row = 7, column = 0, sticky = "E")
label5.grid(row = 8, column = 0, sticky = "E")
label6.grid(row = 3, column = 1)
# Created a text entry box
# for filling or typing the data.
From_field = Entry(root)
To_field = Entry(root)
mode_field = Entry(root)
distance_field = Entry(root)
duration_field = Entry(root)
From_field.grid(row = 1, column = 1, ipadx = "100")
To_field.grid(row = 2, column = 1, ipadx = "100")
mode_field.grid(row = 5, column = 1, ipadx = "50")
distance_field.grid(row = 7, column = 1, ipadx = "100")
duration_field.grid(row = 8, column = 1, ipadx = "100")
# CLEAR Button and attached
# to del_source function
button1 = Button(root, text = "Clear", bg = "light grey",
fg = "black", command = del_From)
# Create a CLEAR Button and attached to del_destination
button2 = Button(root, text = "Clear", bg = "light grey",
fg = "black", command = del_To)
# Create a RESULT Button and attached to find function
button3 = Button(root, text = "Result",
bg = "black", fg = "white",
command = find)
# Create a CLEAR ALL Button and attached to delete_all function
button4 = Button(root, text = "Clear All",
bg = "light grey", fg = "black",
command = delete_all)
# Create a Train Button and attached to train function
button5 = Button(root, text = "Train",
bg = "light grey", fg = "black",
command = train)
# Create a CLEAR Button and attached to del_modes function
button6 = Button(root, text = "Clear",
fg = "black", bg = "light grey",
command = del_modes)
button1.grid(row = 1, column = 2)
button2.grid(row = 2, column = 2)
button3.grid(row = 6, column = 1)
button4.grid(row = 9, column = 1)
button5.grid(row = 4, column = 1)
button6.grid(row = 5, column = 2)
root.mainloop()
Here is a solution using from subprocess import call. All you have to do is replace 'YOUR_FILE_NAME' with... your file name :D
from tkinter import *
from subprocess import call
root=Tk()
root.geometry('200x100')
frame = Frame(root)
frame.pack(pady=20,padx=20)
def open_Menu():
call(["python", "YOUR-FILE-NAME.py"])
btn=Button(frame,text='Open File',command=Open)
btn.pack()
root.mainloop()
What it will look like:
I hope this works for you :D

how can I solve this error: tkinter.TclError: can't invoke "menu" command: application has been destroyed?

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

Categories

Resources