at school we did this program:
import tkinter
ucty = [1234, 5678]
piny = [1234, 4321]
penize = [100, 300]
poradi = None
historie = []
adminUcty = ["admin"]
adminPiny = [1234]
class Pocitani:
def __init__(self, penize, poradi):
self.penize = penize
self.poradi = poradi
def stav(self):
return penize[self.poradi]
def pridej(self, pocetpridan):
self.penize = self.penize + pocetpridan
penize[self.poradi] = self.penize
def odeber(self, pocetodebrat):
if pocetodebrat <= self.penize:
self.penize = self.penize - pocetodebrat
penize[self.poradi] = self.penize
return True
else:
return False
def posli(self, poslat):
if poslat <= self.penize:
self.penize = self.penize - poslat
penize[self.poradi] = self.penize
return True
else:
return False
def jednaSeOCislo(cislo):
try:
int(cislo)
except ValueError:
return False
return True
uživatelského účtu
def zakladniKostra():
global okno2
global vystup1okna2
okno2 = tkinter.Tk()
okno2.geometry("400x650")
canvas = tkinter.Canvas(okno2)
canvas.pack()
canvas.create_polygon(0, 70, 100, 70, 200, 20, fill="red")
canvas.create_polygon(0, 70, 100, 70, 200, 120, fill="red")
canvas.create_polygon(280, 70, 120, 70, 200, 120, fill="blue")
canvas.create_polygon(280, 70, 120, 70, 200, 20, fill="blue")
bankaokna2 = tkinter.Label(okno2, text = "Česká banka", font=("Arial Bold", 35))
bankaokna2.place (x="90", y="130")
nazev1okna2 = tkinter.Label(okno2, text = "Vítej ve svém účtu")
nazev1okna2.place (x="140", y="180")
nazev2okna2 = tkinter.Label(okno2, text = "Vyber možnost co chceš se svým účtem udělat")
nazev2okna2.place (x="50", y="200")
tlacitko1okna2 = tkinter.Button(okno2, text = "Zjistit číslo účtu", command = zjisteniUctu)
tlacitko1okna2.place (x="155", y ="250")
tlacitko2okna2 = tkinter.Button(okno2, text = "Počet peněz na účtu", command = pocetPenez)
tlacitko2okna2.place (x="140", y ="300")
tlacitko3okna2 = tkinter.Button(okno2, text = "Přidání peněz na účet", command = pridejPenizeKostra)
tlacitko3okna2.place (x="135", y ="350")
tlacitko4okna2 = tkinter.Button(okno2, text = "Vybrání peněz z účtu", command = odeberPenizeKostra)
tlacitko4okna2.place (x="135", y ="400")
tlacitko5okna2 = tkinter.Button(okno2, text = "Poslání peněz", command = poslatPenizeKostra)
tlacitko5okna2.place (x="160", y ="450")
tlacitko6okna2 = tkinter.Button(okno2, text = "Výpis historie operací", command = historieOperaci)
tlacitko6okna2.place (x="135", y ="500")
tlacitko7okna2 = tkinter.Button(okno2, text = "Odhlásit se", command = odhlasit)
tlacitko7okna2.place (x="170", y ="550")
vystup1okna2 = tkinter.Label(okno2, text = "")
vystup1okna2.place (x="50", y="600")
def zjisteniUctu():
cisloUctu = ("Číslo účtu je: ", ucty[pinporadi])
vystup1okna2.config(text=cisloUctu, fg="black", font=("Calibri", 15))
def pocetPenez():
vystup = zacni.stav()
cisloUctu = ("Na účtě máš: ", vystup, "KČ")
vystup1okna2.config(text=cisloUctu, fg="black", font=("Calibri", 15))
def pridejPenizeKostra():
global vstuppridej1okno3
global okno3
okno3 = tkinter.Tk()
okno3.geometry("400x150")
nazev1okna3 = tkinter.Label(okno3, text = "Zde si na účet můžeš přidat peníze")
nazev1okna3.place (x="80", y="10")
radekpridej1okna3 = tkinter.Label(okno3, text = "Kolik chceš přidat")
radekpridej1okna3.place (x="30", y="50")
vstuppridej1okno3 = tkinter.Entry(okno3)
vstuppridej1okno3.place (x="150", y ="50")
radekpridej2okna3 = tkinter.Label(okno3, text = "")
radekpridej2okna3.place (x="100", y="150")
tlacitko1okna3 = tkinter.Button(okno3, text = "přidej", command = pridejPenize)
tlacitko1okna3.place (x="175", y ="100")
def pridejPenize():
if jednaSeOCislo(vstuppridej1okno3.get()) == True:
pocetPridej = int(vstuppridej1okno3.get())
if pocetPridej > 0:
vystup = zacni.pridej(pocetPridej)
okno3.destroy()
hlaska = ("Na účet ti bylo přidáno: ", pocetPridej, "KČ")
vystup1okna2.config(text=hlaska, fg="green", font=("Calibri", 15))
historiePrevod = str(pocetPridej)
historieLokal = "+" + historiePrevod
historie.append(historieLokal)
else:
okno3.destroy()
hlaska = ("Zadal jsi zápornou hodnotu. Opakuj akci.")
vystup1okna2.config(text=hlaska, fg="red", font=("Calibri", 15))
else:
okno3.destroy()
hlaska = ("Nezadal jsi číslo. Opakuj akci.")
vystup1okna2.config(text=hlaska, fg="red", font=("Calibri", 15))
def odeberPenizeKostra():
global vstuppridej1okno4
global okno4
okno4 = tkinter.Tk()
okno4.geometry("400x150")
nazev1okna4 = tkinter.Label(okno4, text = "Zde si můžeš z účtu vybrat peníze")
nazev1okna4.place (x="100", y="10")
radekpridej1okna4 = tkinter.Label(okno4, text = "Kolik chceš odebrat:")
radekpridej1okna4.place (x="30", y="50")
vstuppridej1okno4 = tkinter.Entry(okno4)
vstuppridej1okno4.place (x="160", y ="50")
radekpridej2okna4 = tkinter.Label(okno4, text = "")
radekpridej2okna4.place (x="100", y="150")
tlacitko1okna4 = tkinter.Button(okno4, text = "odeber", command = odeberPenize)
tlacitko1okna4.place (x="175", y ="100")
def odeberPenize():
if jednaSeOCislo(vstuppridej1okno4.get()) == True:
pocet = int(vstuppridej1okno4.get())
vstup = zacni.odeber(pocet)
if vstup == True:
okno4.destroy()
hlaska = ("Vybral jsi: ", pocet, "Kč")
vystup1okna2.config(text=hlaska, fg="green", font=("Calibri", 15))
historiePrevod = str(pocet)
historieLokal = "-" + historiePrevod
historie.append(historieLokal)
else:
okno4.destroy()
hlaska = ("Nemáš dostatek peněz na účtě. Opakuj akci.")
vystup1okna2.config(text=hlaska, fg="red", font=("Calibri", 15))
else:
okno4.destroy()
hlaska = ("Nezadal jsi číslo. Opakuj akci.")
vystup1okna2.config(text=hlaska, fg="red", font=("Calibri", 15))
def historieOperaci():
delkaSeznamu = len(historie)
if delkaSeznamu == 0:
okno7 = tkinter.Tk()
okno7.geometry("400x200")
nazev1okna7 = tkinter.Label(okno7, text = "Zatím nebyli provedeny žádné operace", fg="red", font=("Calibri", 15))
nazev1okna7.place (x="70", y="10")
else:
y = 50
delkaOkna = str(100 + (30*len(historie)))
delkaOknaPrevod = "400x"+ delkaOkna
okno7 = tkinter.Tk()
okno7.geometry(delkaOknaPrevod)
nazev1okna7 = tkinter.Label(okno7, text = "Zde vidíte seznam všech provedených operací", fg="black", font=("Calibri", 15))
nazev1okna7.place (x="40", y="10")
for i in historie:
radek1okna7 = tkinter.Label(okno7, text = i)
radek1okna7.place (x="30", y=y)
y = y + 30
def poslatPenizeKostra():
global vstuppridej1okno12
global vstuppridej2okno12
global okno12
global radekpridej4okna12
okno12 = tkinter.Tk()
okno12.geometry("400x210")
nazev1okna12 = tkinter.Label(okno12, text = "Tady můžeš poslat penze na jiný účet")
nazev1okna12.place (x="90", y="10")
radekpridej1okna12 = tkinter.Label(okno12, text = "Zadej číslo účtu")
radekpridej1okna12.place (x="30", y="50")
vstuppridej1okno12 = tkinter.Entry(okno12)
vstuppridej1okno12.place (x="135", y ="50")
radekpridej2okna12 = tkinter.Label(okno12, text = "Zadej částku")
radekpridej2okna12.place (x="45", y="100")
vstuppridej2okno12 = tkinter.Entry(okno12)
vstuppridej2okno12.place (x="135", y ="100")
radekpridej4okna12 = tkinter.Label(okno12, text = "")
radekpridej4okna12.place (x="100", y="135")
tlacitko1okna12 = tkinter.Button(okno12, text = "Poslat peníze", command = poslatPenize)
tlacitko1okna12.place (x="150", y ="175")
def poslatPenize():
if jednaSeOCislo(vstuppridej1okno12.get()) == True:
ucet = int(vstuppridej1okno12.get())
if ucet in ucty:
ucetporadi = ucty.index(ucet)
if jednaSeOCislo(vstuppridej2okno12.get()) == True:
pocetPenez = int(vstuppridej2okno12.get())
vystup = zacni.posli(pocetPenez)
if vystup == True:
castka = penize[ucetporadi]
castka = castka + pocetPenez
penize.pop(ucetporadi)
penize.insert(ucetporadi, castka)
okno12.destroy()
vystup1okna2.config(text="Operace proběhla v pořádku", fg="green", font=("Calibri", 15))
else:
radekpridej4okna12.config(text="Na účtě nemáš dostatek peněz", fg="red", font=("Calibri", 15))
else:
radekpridej4okna12.config(text="Nezadal jsi pěněžní hodnotu v čislech", fg="red", font=("Calibri", 15))
else:
radekpridej4okna12.config(text="Zadal jsi neplatný účet", fg="red", font=("Calibri", 15))
else:
radekpridej4okna12.config(text="Nezadal jsi číslo účtu správně", fg="red", font=("Calibri", 15))
def odhlasit():
okno2.destroy()
historie.clear()
uvodniOkno()
def adminUcet():
adminUcet = vstup1okno8.get()
if adminUcet in adminUcty:
global adminpinporadi
adminpinporadi = adminUcty.index(adminUcet)
adminPin()
else:
adminSpatne()
def adminPin():
if jednaSeOCislo(vstup2okno8.get()) == True:
pin = int(vstup2okno8.get())
if pin == adminPiny[adminpinporadi]:
okno8.destroy()
adminZakladniKostra()
else:
adminSpatne()
else:
radek3okna8.config(text="Do pinu jsi nezadal číslo", fg="red", font=("Calibri", 15))
def adminSpatne():
radek3okna8.config(text="Zadal jsi špatné údaje zkus to znovu", fg="red", font=("Calibri", 15))
def adminPrihlaseni():
global vstup2okno8
global vstup1okno8
global radek3okna8
global okno8
okno1.destroy()
okno8 = tkinter.Tk()
okno8.geometry("400x450")
canvas = tkinter.Canvas(okno8)
canvas.pack()
canvas.create_polygon(0, 70, 100, 70, 200, 20, fill="red")
canvas.create_polygon(0, 70, 100, 70, 200, 120, fill="red")
canvas.create_polygon(280, 70, 120, 70, 200, 120, fill="blue")
canvas.create_polygon(280, 70, 120, 70, 200, 20, fill="blue")
bankaokna8 = tkinter.Label(okno8, text = "Česká banka", font=("Arial Bold", 35))
bankaokna8.place (x="90", y="130")
nazevokna8 = tkinter.Label(okno8, text = "Zadejte své přihlašovací údaje pro vstup do admin režimu")
nazevokna8.place (x="20", y="210")
radek1okna8 = tkinter.Label(okno8, text = "Přihlašovací jméno:")
radek1okna8.place (x="25", y="250")
radek2okna8 = tkinter.Label(okno8, text = "Heslo:")
radek2okna8.place (x="105", y="300")
vstup1okno8 = tkinter.Entry(okno8)
vstup1okno8.place (x="150", y ="250")
vstup2okno8 = tkinter.Entry(okno8)
vstup2okno8.place (x="150", y ="300")
tlacitko1okna8 = tkinter.Button(okno8, text = "přihlásit se", command = adminUcet)
tlacitko1okna8.place (x="120", y ="350")
tlacitko2okna8 = tkinter.Button(okno8, text = "běžné přihlášení", command = adminZpatky)
tlacitko2okna8.place (x="210", y ="350")
radek3okna8 = tkinter.Label(okno8, text = "")
radek3okna8.place (x="100", y="400")
def adminZpatky():
okno8.destroy()
uvodniOkno()
def adminZakladniKostra():
global okno9
global vystup1okna9
okno9 = tkinter.Tk()
okno9.geometry("400x550")
canvas = tkinter.Canvas(okno9)
canvas.pack()
canvas.create_polygon(0, 70, 100, 70, 200, 20, fill="red")
canvas.create_polygon(0, 70, 100, 70, 200, 120, fill="red")
canvas.create_polygon(280, 70, 120, 70, 200, 120, fill="blue")
canvas.create_polygon(280, 70, 120, 70, 200, 20, fill="blue")
bankaokna9 = tkinter.Label(okno9, text = "Česká banka", font=("Arial Bold", 35))
bankaokna9.place (x="90", y="130")
nazev1okna9 = tkinter.Label(okno9, text = "Vítej administrátorském účtu")
nazev1okna9.place (x="110", y="180")
nazev2okna9 = tkinter.Label(okno9, text = "Vyber možnost co chceš udělat")
nazev2okna9.place (x="100", y="200")
tlacitko1okna9 = tkinter.Button(okno9, text = "Chceš přidat účet", command = pridatUcetUcet)
tlacitko1okna9.place (x="145", y ="250")
tlacitko2okna9 = tkinter.Button(okno9, text = "Zajímá tě kolik je dohromady na účtech peněz", command = soucetPenez)
tlacitko2okna9.place (x="65", y ="300")
tlacitko3okna9 = tkinter.Button(okno9, text = "Zajímá tě kolik je ve tvé bance celkem účtů", command = pocetUctu)
tlacitko3okna9.place (x="75", y ="350")
tlacitko4okna9 = tkinter.Button(okno9, text = "Vypiš čísla účtů", command = vypisCislaUctu)
tlacitko4okna9.place (x="150", y ="400")
tlacitko5okna9 = tkinter.Button(okno9, text = "Odhlásit se", command = adminOdhlasit)
tlacitko5okna9.place (x="165", y ="450")
vystup1okna9 = tkinter.Label(okno9, text = "")
vystup1okna9.place (x="100", y="500")
def adminOdhlasit():
okno9.destroy()
uvodniOkno()
def pridatUcetUcet():
global vstuppridej1okno10
global vstuppridej2okno10
global vstuppridej3okno10
global okno10
global radekpridej4okna10
okno10 = tkinter.Tk()
okno10.geometry("400x300")
nazev1okna10 = tkinter.Label(okno10, text = "Tato aplikace ti odebere peníze z účtu")
nazev1okna10.place (x="90", y="10")
radekpridej1okna10 = tkinter.Label(okno10, text = "Zadej číslo účtu")
radekpridej1okna10.place (x="70", y="50")
vstuppridej1okno10 = tkinter.Entry(okno10)
vstuppridej1okno10.place (x="180", y ="50")
radekpridej2okna10 = tkinter.Label(okno10, text = "Zadej Pin")
radekpridej2okna10.place (x="110", y="100")
vstuppridej2okno10 = tkinter.Entry(okno10)
vstuppridej2okno10.place (x="180", y ="100")
radekpridej3okna10 = tkinter.Label(okno10, text = "Zadej počáteční zůstatek")
radekpridej3okna10.place (x="20", y="150")
vstuppridej3okno10 = tkinter.Entry(okno10)
vstuppridej3okno10.place (x="180", y ="150")
radekpridej4okna10 = tkinter.Label(okno10, text = "")
radekpridej4okna10.place (x="100", y="200")
tlacitko1okna10 = tkinter.Button(okno10, text = "přidej", command = pridatUcetOvereniUctu)
tlacitko1okna10.place (x="175", y ="250")
def pridatUcetOvereniUctu():
if jednaSeOCislo(vstuppridej1okno10.get()) == True:
ucet = int(vstuppridej1okno10.get())
if ucet in ucty:
radekpridej4okna10.config(text="Zadal jsi již existující číslo účtu", fg="red", font=("Calibri", 15))
else:
if jednaSeOCislo(vstuppridej2okno10.get()) == True:
if jednaSeOCislo(vstuppridej3okno10.get()) == True:
if int(vstuppridej3okno10.get()) > 0:
ucty.append(int(vstuppridej1okno10.get()))
piny.append(int(vstuppridej2okno10.get()))
penize.append(int(vstuppridej3okno10.get()))
okno10.destroy()
vystup1okna9.config(text="Účet byl přidán", fg="green", font=("Calibri", 15))
else:
radekpridej4okna10.config(text="Zůstatek nesmí být záporný", fg="red", font=("Calibri", 15))
else:
radekpridej4okna10.config(text="Zůstatek musí být číslo", fg="red", font=("Calibri", 15))
else:
radekpridej4okna10.config(text="Pin musí být číslo", fg="red", font=("Calibri", 15))
else:
radekpridej4okna10.config(text="Nezadal jsi číslo do čísla účtu", fg="red", font=("Calibri", 15))
def vypisCislaUctu():
y = 50
delkaOkna = str(100 + (30*len(ucty)))
delkaOknaPrevod = "400x"+ delkaOkna
okno11 = tkinter.Tk()
okno11.geometry(delkaOknaPrevod)
nazev1okna11 = tkinter.Label(okno11, text = "Zde vidíte seznam všech účtů")
nazev1okna11.place (x="110", y="10")
for i in ucty:
radek1okna11 = tkinter.Label(okno11, text = i)
radek1okna11.place (x="30", y=y)
y = y + 30
def soucetPenez():
soucet = 0
for i in penize:
soucet = soucet + i
text = ("Dohromady na účtech je: ", soucet)
vystup1okna9.config(text= text, fg="black", font=("Calibri", 15))
def pocetUctu():
pocet = len(ucty)
if pocet == 0:
text = ("V bance je celkem: ", pocet, " účtů")
elif pocet == 1:
text = ("V bance je celkem: ", pocet, " účet")
elif pocet == 2:
text = ("V bance jsou celkem: ", pocet, " účty")
elif pocet == 3:
text = ("V bance jsou celkem: ", pocet, " účty")
elif pocet == 4:
text = ("V bance jsou celkem: ", pocet, " účty")
else:
text = ("V bance je celkem: ", pocet, " účtů")
vystup1okna9.config(text= text, fg="black", font=("Calibri", 15))
def ucet():
if jednaSeOCislo(vstup1okno1.get()) == True:
ucet = int(vstup1okno1.get())
if ucet in ucty:
global pinporadi
pinporadi = ucty.index(ucet)
pin()
else:
spatne()
else:
radek3okna1.config(text="Do čísla účtu jsi nezadal číslo", fg="red", font=("Calibri", 15))
def pin():
if jednaSeOCislo(vstup2okno1.get()) == True:
pin = int(vstup2okno1.get())
if pin == piny[pinporadi]:
okno1.destroy()
global zacni
zacni = Pocitani(penize[pinporadi], pinporadi)
zakladniKostra()
else:
spatne()
else:
radek3okna1.config(text="Do pinu jsi nezadal číslo", fg="red", font=("Calibri", 15))
def spatne():
radek3okna1.config(text="Zadal jsi špatné údaje zkus to znovu", fg="red", font=("Calibri", 15))
def uvodniOkno():
global okno1
global vstup1okno1
global vstup2okno1
global radek3okna1
okno1 = tkinter.Tk()
okno1.geometry("400x450")
canvas = tkinter.Canvas(okno1)
canvas.pack()
canvas.create_polygon(0, 70, 100, 70, 200, 20, fill="red")
canvas.create_polygon(0, 70, 100, 70, 200, 120, fill="red")
canvas.create_polygon(280, 70, 120, 70, 200, 120, fill="blue")
canvas.create_polygon(280, 70, 120, 70, 200, 20, fill="blue")
bankaokna1 = tkinter.Label(okno1, text = "Česká banka", font=("Arial Bold", 35))
bankaokna1.place (x="90", y="130")
nazevokna1 = tkinter.Label(okno1, text = "Zadejte své přihlašovací údaje")
nazevokna1.place (x="100", y="210")
radek1okna1 = tkinter.Label(okno1, text = "Číslo účtu:")
radek1okna1.place (x="30", y="250")
radek2okna1 = tkinter.Label(okno1, text = "Pin:")
radek2okna1.place (x="70", y="300")
vstup1okno1 = tkinter.Entry(okno1)
vstup1okno1.place (x="100", y ="250")
vstup2okno1 = tkinter.Entry(okno1)
vstup2okno1.place (x="100", y ="300")
tlacitko1okna1 = tkinter.Button(okno1, text = "přihlásit se", command = ucet)
tlacitko1okna1.place (x="120", y ="350")
tlacitko2okna1 = tkinter.Button(okno1, text = "admin", command = adminPrihlaseni)
tlacitko2okna1.place (x="210", y ="350")
radek3okna1 = tkinter.Label(okno1, text = "")
radek3okna1.place (x="100", y="400")
uvodniOkno()
and I got an assignment that I have: The design of the application is wrong, because you use the class Pocitani, but you create a single object from this class. Important data of the application is contained in the lists of honor, pin, money. This contradicts not only the assignment of the project, but above all the principle of object-oriented programming. Fix the project so that there is a single account list that will contain all accounts as instances of the Ucet class. This Account class will be created from your Account class, but it will also contain the account number, account pin and account history (this will not be deleted when you log out of the account).
How can I solve this problem?
How can I solve this problem?
Related
I ran into this problem and don't know how to solve it.
When I press the "generate" button(self.gen), my picture 11 changes to picture 22.
BUT I need the image 11 to NOT change when the button is clicked and an error occurs(messagebox.showerror pops up) OR so that after closing the messagebox.showerror, picture 22 changes to 11
import tkinter
from tkinter import *
from tkinter import messagebox, scrolledtext
from PIL import Image, ImageTk
from random import randint
class App:
def __init__(self):
self.window = tkinter.Tk()
self.window.title("Генератор")
self.window['bg'] = '#FFF5EE'
self.window.geometry('660x550')
self.window.resizable(False,False)
self.lb1 = Label(self.window, text="Enter:", background='#FFF5EE', font = ("Comic Sans MS", 14))
self.lb1.grid(column=0, row=2)
self.lb2 = Label(self.window, text="min(1-999)",background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb2.grid(column=1, row=3)
self.lb3 = Label(self.window, text="max(1-999)", background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb3.grid(column=1, row=4)
self.lb4 = Label(self.window, text="amount of numbers", background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb4.grid(column=4, row=3)
self.txt2 = Entry(self.window,width=10, borderwidth=3)
self.txt2.grid(column=2, row=3)
self.txt3 = Entry(self.window,width=10, borderwidth=3)
self.txt3.grid(column=2, row=4)
self.txt4 = Entry(self.window,width=10, borderwidth=3)
self.txt4.grid(column=5, row=3)
self.scrolltxt = scrolledtext.ScrolledText(self.window, width=30, height=3, borderwidth=7, state='disabled')
self.scrolltxt.grid(row=1, column=2, columnspan=3, padx=10, pady=10)
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
self.photo = ImageTk.PhotoImage(self.image)
self.gen = Button(self.window, width = 15, text="Generate", command = lambda:[self.clicked1(), self.gen1()])
self.gen.grid(row=4, column=6)
self.canvas = tkinter.Canvas(self.window, height=230, width=230)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw', image = self.photo)
self.btn = Button(self.window, width = 15, text="Delete", command=lambda:[self.delete(),self.clicked2()])
self.btn.grid(column=6, row=5)
self.exit = Button(self.window, width = 15, text="Exit", command=lambda: [self.clicked3(), quit()])
self.exit.grid(column=6, row=6)
self.i = Button(self.window, width = 8,text = "i", font = ("Eras Bold ITC", 10) , command = self.inf)
self.i.grid(row = 0,column = 6)
self.window.mainloop()
def clicked1(self):
print("clicked1")
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\22.png")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)
def gen1(self):
try:
MinNum = int(self.txt2.get())
MaxNum = int(self.txt3.get())
Num = int(self.txt4.get())
except ValueError:
messagebox.showerror("Error", "Якщо не рвешся у висоту, шишок не наб'єш.")
else:
Nums = " "
if MinNum <= MaxNum:
i = 0
while i < Num:
numOne = randint(MinNum, MaxNum)
Nums = Nums + ' ' + str(numOne)
i += 1
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete(1.0, END)
self.scrolltxt.insert(INSERT, str(Nums) + "\n")
self.scrolltxt.config(state="disabled") # disable the text box
else:
messagebox.showerror("Error", "Якщо не рвешся у висоту, шишок не наб'єш.")
def delete(self):
self.txt4.delete(0, END)
self.txt3.delete(0, END)
self.txt2.delete(0, END)
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete(1.0, END)
self.scrolltxt.config(state="disabled") # disable the text box
def clicked2(self):
print("clicked2")
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)
def clicked3(self):
messagebox.showinfo("Це Звірополіс. Будь-хто може бути будь-ким.", "Хто сказав, що неможливе недосяжне?! Пошкодуйте цього дивака.")
def inf(self):
messagebox.showinfo("Info", "Лисичка замахалась")
app = App()
is it possible to implement this through tkinter?
Change the command argument of self.gen to:
self.gen = Button(self.window, width = 15, text="Generate", command=self.gen1)
And move the call to clicked1() into the if block of gen1() so it will only be called when conditions are accepted
def gen1(self):
try:
MinNum = int(self.txt2.get())
MaxNum = int(self.txt3.get())
Num = int(self.txt4.get())
except ValueError:
messagebox.showerror(
"Error",
"Якщо не рвешся у висоту, шишок не наб'єш."
)
else:
Nums = " "
if MinNum <= MaxNum:
i = 0
while i < Num:
numOne = randint(MinNum, MaxNum)
Nums = Nums + ' ' + str(numOne)
i += 1
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete(1.0, END)
self.scrolltxt.insert(INSERT, str(Nums) + "\n")
self.scrolltxt.config(state="disabled") # disable the text box
self.clicked1() # call the 'clicked1' method
else:
messagebox.showerror(
"Error",
"Якщо не рвешся у висоту, шишок не наб'єш."
)
please help me I have tried so much things but this doesn't work...
I'm beginner in POO (my code is so ugly wtf) and i don't understand why my code doesn't work ...
I give you a code which works and a code which doesn't work while they used the same attribute ...
this code works:
from tkinter import *
import tkinter as tk
import time
root = Tk()
x = 0
y = 0
def move_window(event):
# global x, y
print(x, y)
root.geometry('+{0}+{1}'.format(event.x_root - x, event.y_root - y))
root.overrideredirect(True) # turns off title bar, geometry
root.geometry('400x200+200+200') # set new geometry
# make a frame for the title bar
title_bar = Frame(root, bg='white', relief='raised', bd=2)
# put a close button on the title bar
close_button = Button(title_bar, text='X', command=root.destroy)
# a canvas for the main area of the window
window = Canvas(root, bg='black')
# pack the widgets
title_bar.pack(expand=1, fill=X)
close_button.pack(side=RIGHT)
window.pack(expand=1, fill=BOTH)
# bind title bar motion to the move window function
def setxy(event):
global x,y
x=event.x_root - root.winfo_x()
y=event.y_root - root.winfo_y()
# print(x,y)
return x,y;
title_bar.bind('<1>',setxy)
title_bar.bind('<B1-Motion>', move_window)
root.mainloop()
and this one doesn't :
import os
import tkinter as tk
from tkinter import *
from tkinter import font
win = tk.Tk()
win.overrideredirect(1)
# def realcenter( o, w, h ) ->'o(w,h) centered on screen':
# x = o.winfo_screenwidth( ) - w
# y = o.winfo_screenheight( ) - h
# o.geometry( f'{w}x{h}+{int( x/2 )}+{int( y/2 )}' )
# def restore( ev ):
# win.overrideredirect( 0 )
# def unrestore( ev ):
# win.overrideredirect( 1 )
# win.geometry( '500x525' )
# realcenter( win, 500, 525)
# win.update_idletasks()
# win.overrideredirect( 1 )
# win.bind( '<F1>', restore )
# win.bind( '<F2>', unrestore )
font1 = font.Font(family = 'Helvetica', size = 15)
font3 = font.Font(family = 'Helvetica', size = 8, weight = 'bold')
font2 = font.Font(family = 'Helvetica', size = 20, weight = 'bold')
def aaa(colora, colorb, colorc, colord, colore, colorf):
Dark = Theme('#18181F','#0C0C0F',"#505063",'#D1DDFF','#D12319',"#D1665F")
Ecrire('',Light)
def aaaa(colora, colorb, colorc, colord, colore, colorf):
Light = Theme('#F1EDF5','#D1D2E8',"#EDD5EB",'#323133','#6F2EB0',"#C47ED6")
Ecrire('',Dark)
def strl(list):
list ="".join(list)
return list
# menubar = Menu(win)
# win.config(menu=menubar)
# menufichier = Menu(menubar,tearoff=0)
# menubar.add_cascade(label="Theme", menu=menufichier)
# menufichier.add_command(label=" Dark mode",font = font3,command =lambda: aaa('#18181F','#0C0C0F',"#505063",'#D1DDFF','#D12319',"#D1665F"))
# menufichier.add_command(label=" Light mode",font = font3,command =lambda: aaaa('#F1EDF5','#D1D2E8',"#EDD5EB",'#323133','#6F2EB0',"#C47ED6"))
pixel = tk.PhotoImage(width=1, height=1)
a =95
b =95
theme = 0
t = 0
ecrit = []
nombre_de_multdiv = 0
nombre_de_sous_add = 0
def Del(self):
global ecrit
del ecrit[-1]
affichage = strl(ecrit)
self.label1['text'] = affichage
self.label1.place(anchor = 'e', x = 450, y = 75)
def Del_all(self):
global ecrit
del ecrit[:]
affichage = strl(ecrit)
self.label1['text'] = affichage
self.label1.place(anchor = 'e', x = 450, y = 75)
def Ecrire(symbole,self):
ecrit.append(symbole)
affichage = strl(ecrit)
self.label1['text'] = affichage
self.label1.place(anchor = 'e', x = 450, y = 75)
def Ecrire_Resulat(valeur,self):
valeur = strl(valeur)
self.label1['text'] = valeur
def Calcul(self):
global nombre_de_multdiv
global nombre_de_sous_add
for i in range(len(ecrit)):
if ecrit[i] == '/' or ecrit[i] == '*':
nombre_de_multdiv +=1
for i in range(len(ecrit)):
if ecrit[i] == '+' or ecrit[i] == '-':
nombre_de_sous_add +=1
for i in range(nombre_de_multdiv):
for i in range(len(ecrit)):
if ecrit[i] == '*' or ecrit[i] == '/':
numero = i
nb = i
nbb = i
for i in range(len(ecrit)-numero-1):
if ecrit[i+1 + numero] != '/' and ecrit[i+1 + numero] != '*' and ecrit[i+1 + numero] != '+' and ecrit[i+1 + numero] != '-':
nb +=1
elif ecrit[i+1+numero] == '/' or ecrit[i+1+numero] == '*' or ecrit[i+1+numero] == '+' or ecrit[i+1+numero] == '-':
break
for i in range(numero):
i = -i
if ecrit[i-1+numero] != '/' and ecrit[i-1+numero] != '*' and ecrit[i-1+numero] != '+' and ecrit[i-1+numero] != '-':
nbb -=1
elif ecrit[i-1+numero] == '/' or ecrit[i-1+numero] == '*' or ecrit[i-1+numero] == '+' or ecrit[i-1+numero] == '-':
break
nombre1 = "".join(ecrit[numero+1:nb+1])
nombre1 = float(nombre1)
nombre2 = "".join(ecrit[nbb:numero])
nombre2 = float(nombre2)
if ecrit[numero] =='*':
resultat = nombre1 * nombre2
if resultat == int(resultat):
resultat = int(resultat)
resultat = list(str(resultat))
else:
resultat = nombre2 / nombre1
if resultat == int(resultat):
resultat = int(resultat)
resultat = list(str(resultat))
del ecrit[nbb:nb+1]
for i in range(len(resultat)):
ecrit.insert(nbb+i,resultat[i])
break
for i in range(nombre_de_sous_add):
for i in range(len(ecrit)):
if ecrit[i] == '+' or ecrit[i] == '-':
numero = i
nb = i
nbb = i
for i in range(len(ecrit)-numero-1):
if ecrit[i+1 + numero] != '/' and ecrit[i+1 + numero] != '*' and ecrit[i+1 + numero] != '+' and ecrit[i+1 + numero] != '-':
nb +=1
elif ecrit[i+1+numero] == '/' or ecrit[i+1+numero] == '*' or ecrit[i+1+numero] == '+' or ecrit[i+1+numero] == '-':
break
for i in range(numero):
i = -i
if ecrit[i-1+numero] != '/' and ecrit[i-1+numero] != '*' and ecrit[i-1+numero] != '+' and ecrit[i-1+numero] != '-':
nbb -=1
elif ecrit[i-1+numero] == '/' or ecrit[i-1+numero] == '*' or ecrit[i-1+numero] == '+' or ecrit[i-1+numero] == '-':
break
nombre1 = "".join(ecrit[numero+1:nb+1])
nombre1 = float(nombre1)
nombre2 = "".join(ecrit[nbb:numero])
nombre2 = float(nombre2)
if ecrit[numero] =='+':
resultat = nombre1 + nombre2
if resultat == int(resultat):
resultat = int(resultat)
resultat = list(str(resultat))
else:
resultat = nombre2 - nombre1
if resultat == int(resultat):
resultat = int(resultat)
resultat = list(str(resultat))
del ecrit[nbb:nb+1]
for i in range(len(resultat)):
ecrit.insert(nbb+i,resultat[i])
break
Ecrire_Resulat(ecrit,self)
class Theme():
def move_window(self,event):
# global x, y
print(self.x, self.y)
win.geometry('+{0}+{1}'.format(event.x_win - self.x, event.y_win - self.y))
def set_xy(self,event):
self.x=event.x_win - win.winfo_x()
self.y=event.y_win - win.winfo_y()
# print(x,y)
return self.x,self.y;
def boutontheme(self,colora, colorb, colorc, colord, colore, colorf):
self.openmenu(colora, colorb, colorc, colord, colore, colorf)
if self.t == 0:
Light = Theme('#F1EDF5','#D1D2E8',"#EDD5EB",'#323133','#6F2EB0',"#915ec4")
self.t = 1
else:
Dark = Theme('#18181F','#0C0C0F',"#505063",'#D1DDFF','#D12319',"#D1665F")
self.t = 0
def openmenu(self,colora, colorb, colorc, colord, colore, colorf):
if self.ouvert == False:
self.b_theme.config(bg = colore)
if self.t == 0:
self.b_theme_dark = tk.Button(win,state=DISABLED, text = 'Dark theme',font = font3,borderwidth=0, highlightthickness=0,compound="c",image = pixel,height = 20,width = 70,activebackground =colore,bg =colora,fg = colord,command = lambda: self.boutontheme(colora, colorb, colorc, colord, colore, colorf))
self.b_theme_light = tk.Button(win,state=NORMAL, text = 'Light theme',font = font3,borderwidth=0, highlightthickness=0,compound="c",image = pixel,height = 20,width = 70,activebackground =colore,bg =colora,fg = colord,command = lambda: self.boutontheme(colora, colorb, colorc, colord, colore, colorf))
else:
self.b_theme_dark = tk.Button(win,state=NORMAL, text = 'Dark theme',font = font3,borderwidth=0, highlightthickness=0,compound="c",image = pixel,height = 20,width = 70,activebackground =colore,bg =colora,fg = colord,command = lambda: self.boutontheme(colora, colorb, colorc, colord, colore, colorf))
self.b_theme_light = tk.Button(win,state=DISABLED, text = 'Light theme',font = font3,borderwidth=0, highlightthickness=0,compound="c",image = pixel,height = 20,width = 70,activebackground =colore,bg =colora,fg = colord,command = lambda: self.boutontheme(colora, colorb, colorc, colord, colore, colorf))
self.b_theme_dark.place(anchor = 'nw', x = 5, y = 25)
self.b_theme_light.place(anchor = 'nw', x = 5, y = 45)
self.ouvert = True
return;
if self.ouvert == True:
self.b_theme.config(bg = colorb)
self.b_theme_dark.destroy()
self.b_theme_light.destroy()
self.ouvert = False
return;
# def closemenu(self):
# self.b_theme_dark.forget()
# self.b_theme_light.forget()
# ouvert = False
def __init__(self,colora, colorb, colorc, colord, colore, colorf):
if colora == '#18181F':
self.t = 0
else:
self.t = 1
self.ouvert = False
self.x = 0
self.y=0
#creation menu
self.canvas_menu = Canvas(win, width =500, height =25, bg = colora, borderwidth=0, highlightthickness=0)
self.exit = Canvas(bg = colora,borderwidth=0, highlightthickness=0)
self.exit.create_oval(0,0,20,20, fill= colore,width = 0)
self.exit.create_text(10, 10, text="x", fill = colord, font= font3)
self.exit.bind("<Button-1>", lambda e: win.destroy())
#affichage menu
self.exit.place(anchor = 'nw', x = 475, y = 2)
self.canvas_menu.grid(row = 0,column = 0, columnspan = 5)
#creation des canvas
self.canvas_screen = Canvas(win, width =500, height =100, bg =colorb,borderwidth=0, highlightthickness=0)
self.canvas_keyb_num = Canvas(win, width =300, height =400, bg =colorb,borderwidth=0, highlightthickness=0)
self.canvas_keyb_op = Canvas(win, width =200, height =400, bg =colorb,borderwidth=0, highlightthickness=0)
#affchage des canvas
self.canvas_screen.grid(row = 1,column = 0, columnspan = 5)
self.canvas_keyb_num.grid(row = 2,column = 0, columnspan = 3, rowspan = 4)
self.canvas_keyb_op.grid(row = 2,column = 3, columnspan = 2, rowspan = 4)
# creation des boutons
self.b1 = Button(win, text ='1',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('1',self))
self.b2 = Button(win, text ='2',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('2',self))
self.b3 = Button(win, text ='3',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('3',self))
self.b4 = Button(win, text ='4',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('4',self))
self.b5 = Button(win, text ='5',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('5',self))
self.b6 = Button(win, text ='6',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('6',self))
self.b7 = Button(win, text ='7',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('7',self))
self.b8 = Button(win, text ='8',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('8',self))
self.b9 = Button(win, text ='9',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('9',self))
self.b_point = Button(win, text ='.',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('.',self))
self.b0 = Button(win, text ='0',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('0',self))
self.b_plus = Button(win, text ='+',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('+',self))
self.b_moins = Button(win, text ='-',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('-',self))
self.b_fois = Button(win, text ='*',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('*',self))
self.b_diviser = Button(win, text ='/',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Ecrire('/',self))
self.b_del = Button(win, text ='DEL',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Del(self))
self.b_del_all = Button(win, text ='CE',borderwidth=0, highlightthickness=0, bg = colora,activebackground =colorc,foreground=colord,compound="c",image = pixel,height = a,width = b ,font = font1,command=lambda: Del_all(self))
self.b_egale = Button(win, text ='=',borderwidth=0, highlightthickness=0, bg = colore,activebackground =colorf,foreground=colord,compound="c",image = pixel,height = a,width = 295 ,font = font1,command= lambda: Calcul(self))
#affichage des nombres
#colone 1
self.b7.grid(column = 0, row = 2)
self.b4.grid(column = 0, row = 3)
self.b1.grid(column = 0, row = 4)
self.b_point.grid(column = 0, row = 5)
#colone 2
self.b8.grid(column = 1, row = 2)
self.b5.grid(column = 1, row = 3)
self.b2.grid(column = 1, row = 4)
self.b0.grid(column = 1, row = 5)
#colone 3
self.b9.grid(column = 2, row = 2)
self.b6.grid(column = 2, row = 3)
self.b3.grid(column = 2, row = 4)
#operateurs
self.b_plus.grid(column = 3, row = 2)
self.b_moins.grid(column = 4, row = 2)
self.b_fois.grid(column = 3, row = 3)
self.b_diviser.grid(column = 4, row = 3)
self.b_del.grid(column = 3, row = 4)
self.b_del_all.grid(column = 4, row = 4)
self.b_egale.grid(column = 2, row = 5,columnspan = 3)
#ecriture
self.label1 = tk.Label(win, text = '', justify = tk.RIGHT,font = font2,bg =colorb,fg = colord)
self.label1.place(anchor = 'e', x = 450, y = 75)
self.b_theme = tk.Button(win, text = 'Themes',font = font3,bg =colorb,fg = colord,borderwidth=0, highlightthickness=0,compound="c",image = pixel,height = 20,width = 50,activebackground =colore,command= lambda: self.openmenu(colora, colorb, colorc, colord, colore, colorf))
self.b_theme.place(anchor = 'nw', x = 5, y = 2)
self.canvas_menu.bind('<1>', self.set_xy)
# bind title bar motion to the move window function
self.canvas_menu.bind('<B1-Motion>', self.move_window)
# b_theme_dark.config(bg =colorb,fg = colord, activebackground =colore)
# b_theme_light.config(bg =colorb,fg = colord, activebackground =colore)
# menufichier.config(activebackground = colorc,bg = colora,fg = colord)
if theme == 0:
Dark = Theme('#18181F','#0C0C0F',"#505063",'#D1DDFF','#D12319',"#D1665F")
else:
Light = Theme('#F1EDF5','#D1D2E8',"#EDD5EB",'#323133','#6F2EB0',"#915ec4")
win.title('calculator')
#pour un future menu
# bouton.config(state=DISABLED)
# bouton.config(state=NORMAL)
win.resizable(height=False,width=False)
win.mainloop()
set on line 9- 10 this:
GLOBAL_X = 0
GLOBAL_Y = 0
at line 242 this:
def move_window(self, event):
global GLOBAL_X, GLOBAL_Y
x = win.winfo_pointerx() - GLOBAL_X
y = win.winfo_pointery() - GLOBAL_Y
win.geometry("+%d+%d" % (x,y))
def set_xy(self, event):
global GLOBAL_X, GLOBAL_Y
GLOBAL_X= win.winfo_rootx()- event.widget.winfo_rootx() + event.x
GLOBAL_Y = win.winfo_rooty() - event.widget.winfo_rooty() + event.y
and don forget on line 448 this:
self.canvas_menu.bind("<Button-1>", self.set_xy)
Replace event.x_name_of_the_window with event.x_root.
I want to clear the output result of the equation. But when I press the clear button it gives an error
"NameError: name 'CalculationOutput' is not defined"
How do I solve this problem.
import tkinter as tk
compression = ""
GuiRoot = tk.Tk()
MainCanvas = tk.Canvas(GuiRoot, width=500, height=400, relief="raised")
MainCanvas.pack()
DesignText1 = tk.Label(GuiRoot, text="Calculate the Square Root")
DesignText1.config(font=("halvetica", 14))
MainCanvas.create_window(250, 25, window=DesignText1)
DesignText2 = tk.Label(GuiRoot, text="Type your number")
DesignText2.config(font=("halvetica", 10))
MainCanvas.create_window(250, 100, window=DesignText2)
UserEntryBox = tk.Entry(GuiRoot)
MainCanvas.create_window(250, 200, window=UserEntryBox)
def GetSquareRoot():
x = UserEntryBox.get()
DesignText3 = tk.Label(GuiRoot, text="The Square Root of " + x + ' is:', font=("halvetica", 10))
MainCanvas.create_window(250, 260, window=DesignText3)
CalculationOutput = tk.Label(GuiRoot, text=float(x)**0.5, font=("halvetica", 10, "bold"))
MainCanvas.create_window(250, 280, window=CalculationOutput)
CalculationButton = tk.Button(text="Get the Square Root", command=GetSquareRoot, bg="brown", fg='white', font=('halvetica', 9, 'bold'))
MainCanvas.create_window(250, 230, window=CalculationButton)
def ClearButtonFunc():
global compression
compression = ""
CalculationOutput.set("")
ClearButton = tk.Button(GuiRoot, text="Clear Text", command=ClearButtonFunc)
MainCanvas.create_window(250, 320, window=ClearButton)
GuiRoot.mainloop()
I am trying to take input name, email and password from user and print it in screen. But the variable is took is showing none every time. Can anyone solve my problem?
import tkinter as tk
import tkinter.font as f
r = tk.Tk()
name=''
email=''
password=''
def Print():
print("Name is",name)
print("Email is",email)
print("Password is",password)
f=tk.Frame(r,height=600,width=900)
f.pack()
name = tk.Label(f, text = "Name").place(x = 30,y = 50)
email = tk.Label(f, text = "Email").place(x = 30, y = 90)
password = tk.Label(f, text = "Password").place(x = 30, y = 130)
sbmitbtn = tk.Button(f, text = "Submit",activebackground = "pink", activeforeground = "blue",command=lambda:[Print(),f.destroy()]).place(x = 30, y = 170)
e1 = tk.Entry(f,textvariable=name).place(x = 80, y = 50)
e2 = tk.Entry(f,textvariable=email).place(x = 80, y = 90)
e3 = tk.Entry(f,textvariable=password).place(x = 95, y = 130)
r.mainloop()
you can use StringVar to get the string. the textvariable in your Label needs to be a Tkinter variable, quote:
"
textvariable= Associates a Tkinter variable (usually a StringVar) to
the contents of the entry field. (textVariable/Variable)
you can read more here
import tkinter as tk
import tkinter.font as f
r = tk.Tk()
name = tk.StringVar()
email = tk.StringVar()
password = tk.StringVar()
def Print():
print("Name is", name.get())
print("Email is", email.get())
print("Password is", password.get())
f = tk.Frame(r, height=600, width=900)
f.pack()
tk.Label(f, text="Name").place(x=30, y=50)
tk.Label(f, text="Email").place(x=30, y=90)
tk.Label(f, text="Password").place(x=30, y=130)
sbmitbtn = tk.Button(f, text="Submit", activebackground="pink", activeforeground="blue",
command=lambda: [Print(), f.destroy()]).place(x=30, y=170)
e1 = tk.Entry(f, textvariable=name).place(x=80, y=50)
e2 = tk.Entry(f, textvariable=email).place(x=80, y=90)
e3 = tk.Entry(f, textvariable=password).place(x=95, y=130)
r.mainloop()
I am a GCSE student in year 10 so I have only just started my course and proper coding. We were set a task to create a game called botmod where you control a character that collects people then returns them to a base. I created the game fine using general knowledge and getting help from Google for what I didn't understand. Once I finished the main program I started on creating a start menu where the user can set their own variables for the game such as grid size etc. once I had implemented this with the main program this is where the issue began.
Once I go through both menus and select all options the program stops responding then crashes.
I am aware this code is extremely messy and that I should not be using global variables or at least be avoiding them as much as possible but we haven't properly started OOP yet so I decided against diving into it.
Thank you in advance for the help.
from tkinter import *
from random import choice, shuffle
def Ending_Conditions():
global Player_Power, Players_Collected
if Players_Collected == 3:
Game_End("YOU WIN!")
elif Player_Power <= 0 and Players_Collected != 3:
Game_End("Game Over")
def Game_End(End_Option):
global Playing_Game, Game_Finished
if End_Option == "EXIT":
Playing_Game = False
Root.destroy()
else:
Game_Finished = True
Game_Canvas.create_rectangle(120, 120, 480, 300, fill = "#ffffff")
Game_Canvas.create_text(300, 210, text = End_Option, font = ('Abadi', 35, "bold"))
Continue_Button = Button(Root, text = 'Continue', command = lambda: Game_Restart('CONTINUE'))
Exit_Button = Button(Root, text = 'Exit', command = lambda: Game_Restart('EXIT'))
Continue_Button.pack()
Exit_Button.pack()
def Game_Restart(Restart_Option):
if Restart_Option == 'CONTINUE':
Root.destroy()
Restart_Game = True
if Restart_Option == 'EXIT':
Game_End('EXIT')
def Paused_UI():
global Game_Paused, Close_PausedUI
Close_PausedUI = Button(Root, text = 'Exit', command = Close_Paused_UI)
Close_PausedUI.pack()
Game_Paused = True
def Close_Paused_UI():
global Game_Paused, Close_PausedUI
Close_PausedUI.pack_forget()
Game_Paused = False
def Generate_Game():
global Game_Canvas, Game_Player, Game_Base, Player_Power, Power_Counter, People_Locations, Game_Paused, All_People, Game_Grid
Current_Colour = 0
Grid_Colour = []
Player_PosX, Player_PosY, Player_Storage, Players_Collected = 30, 30, 0, 0,
People_Locations = {0:[150, 450, 0], 1:[270, 330, 1], 2:[450, 90, 2]}
Game_Finished = False
# Generate UI
Game_Menu = Button(Root, text = 'Menu', command = Paused_UI)
Game_Menu.pack()
# Define grid colours
Grid_Colours = ['#009446', '#D4F0FF', '#5f6365']
# Generate power counter and pack canvas
Power_Counter = Label(Root, text = Player_Power)
Power_Counter.pack()
Game_Canvas.pack()
# Generate Grid and Colours
for y in range(Game_Grid):
for x in range(Game_Grid):
shuffle(Grid_Colours)
Game_Grid = Game_Canvas.create_rectangle(0+60*x, 0+60*y, 60+60*x, 60+60*y, fill = Grid_Colours[0])
Grid_Colour.append(Grid_Colours[0])
# Generate Robot Player
Game_Player = Game_Canvas.create_text(Player_PosX, Player_PosY, text = "R", font = ('Abadi', 35, "bold"))
# Generate Player Base
Game_Base = Game_Canvas.create_text(450, 330, text = "B", font = ('Abadi', 35, "bold"))
# Generate People
for i in range(Game_People):
Person_Location = People_Locations[0+i]
Game_Person = Game_Canvas.create_text(Person_Location[0], Person_Location[1], text = "P", font = ('Abadi', 35, "bold"), tag = 'Game_Person')
All_People = Game_Canvas.find_withtag('Game_Person')
All_People = list(All_People)
def Move_Player(event):
global Game_Canvas, Game_Player, Game_Base, Player_PosY, Player_PosX, Current_Colour, Player_Power, Power_Counter, Player_Storage, Players_Collected, Game_Finished, Current_Person
if event.char.lower() == '\x1b' and Game_Paused == False:
Paused_UI()
elif event.char.lower() == '\x1b' and Game_Paused == True:
Close_Paused_UI()
if Game_Paused == False and Game_Finished != True:
Movement_Value = Movement_Values[event.char.lower()]
if Player_PosX != Movement_Value[0] and Player_PosY != Movement_Value[1]:
# Detect current grid colour and configure power accordingly
Player_Power = Player_Power - Power_Values[Grid_Colour[Current_Colour]]
Power_Counter.configure(text = Player_Power)
Current_Colour = Current_Colour + Movement_Value[4]
# Delete the player then recreate in its new position
Game_Canvas.delete(Game_Player)
Player_PosX, Player_PosY = Player_PosX + Movement_Value[2], Player_PosY + Movement_Value[3]
Game_Player = Game_Canvas.create_text(Player_PosX, Player_PosY, text = "R", font = ('Abadi', 35, "bold"))
# Detect Person
for item in People_Locations:
Person_Location = People_Locations[item]
if Player_PosX == Person_Location[0] and Player_PosY == Person_Location[1] and Player_Storage != 1:
Current_Person = Person_Location[2]
Game_Canvas.delete(All_People[Current_Person])
Player_Storage += 1
if Player_PosX == 450 and Player_PosY == 330:
if Player_Storage == 1:
Player_Storage -= 1
Players_Collected += 1
Clear_Current = People_Locations[Current_Person]
Clear_Current = Clear_Current[2]
People_Locations.pop(Clear_Current)
Ending_Conditions()
def Start_Game():
global Start_Canvas
Start_Canvas = Canvas(Root, width = 600, height = 500, bd=0, highlightthickness=0, bg = '#ffffff')
Start_Canvas.pack()
Title = Start_Canvas.create_text(300, 163, text = "BOTMOD", font = ('Cinema Gothic BTN Shadow', 75, 'normal'))
Play_Button = Button(text = "PLAY", width = 10, font=('Arial', 15), command = Play_Game)
Play_Button = Start_Canvas.create_window(300, 325, window = Play_Button)
Exit_Button = Button(text = "EXIT", width = 10, font=('Arial', 15), command = lambda: Game_End("EXIT"))
Exit_Button = Start_Canvas.create_window(300, 375, window = Exit_Button)
def Play_Game():
global Menu_Canvas, Grid_Entry, Power_Entry, People_Entry
Start_Canvas.destroy()
Menu_Canvas = Canvas(Root, width = 600, height = 500, bd=0, highlightthickness=0, bg = '#C0C0C0')
Menu_Canvas.pack()
Title_Rectangle = Menu_Canvas.create_rectangle(120, 10, 480, 100, fill = '#000000')
Slider_Rectangle = Menu_Canvas.create_rectangle(120, 110, 480, 430, fill = '#000000')
Footer_Rectangle = Menu_Canvas.create_rectangle(120, 440, 480, 490, fill = '#000000')
Title = Menu_Canvas.create_text(300, 55, text = "BOTMOD", font = ('Cinema Gothic BTN Shadow', 55, 'normal'), fill = '#ffffff')
Description_Text = Label(text = "Set Game Options", font=('Arial', 15, 'bold'), bg = '#000000', fg = '#ffffff')
Description_Text = Menu_Canvas.create_window(300, 145, window = Description_Text)
Power_Text = Label(text = "Robot Power", font=('Cinema Gothic BTN Shadow', 15), bg = '#000000', fg = '#ffffff')
Power_Text = Menu_Canvas.create_window(300, 195, window = Power_Text)
Power_Entry = Scale(from_= 50, to = 350, orient = HORIZONTAL, bg = '#000000', fg = '#ffffff', highlightthickness=0, bd = 0)
Power_Entry = Menu_Canvas.create_window(300, 225, window = Power_Entry)
People_Text = Label(text = "Person Count", font=('Cinema Gothic BTN Shadow', 15), bg = '#000000', fg = '#ffffff')
People_Text = Menu_Canvas.create_window(300, 280, window = People_Text)
People_Entry = Scale(from_= 3, to = 10, orient = HORIZONTAL, bg = '#000000', fg = '#ffffff', highlightthickness=0, bd = 0, state=DISABLED)
People_Entry = Menu_Canvas.create_window(300, 310, window = People_Entry)
Grid_Text = Label(text = "Grid Count", font=('Cinema Gothic BTN Shadow', 15), bg = '#000000', fg = '#ffffff')
Grid_Text = Menu_Canvas.create_window(300, 365, window = Grid_Text)
Grid_Entry = Scale(from_= 5, to = 15, orient = HORIZONTAL, bg = '#000000', fg = '#ffffff', highlightthickness=0, bd = 0)
Grid_Entry = Menu_Canvas.create_window(300, 395, window = Grid_Entry)
Play_Button = Button(text = "OK", width = 15, font=('Cinema Gothic BTN Shadow', 10), command = lambda: Init_Game("DEFAULT"), bg = '#000000', fg = '#ffffff')
Play_Button = Menu_Canvas.create_window(400, 465, window = Play_Button)
PlayWD_Button = Button(text = "Use Defaults", width = 15, font=('Cinema Gothic BTN Shadow', 10), command = lambda: Init_Game("CUSTOM"), bg = '#000000', fg = '#ffffff')
PlayWD_Button = Menu_Canvas.create_window(200, 465, window = PlayWD_Button)
def Init_Game(Game_Options):
global Grid_Count, Player_PosY, Player_PosX, Game_Paused, Game_Finished, Playing_Game, Player_Power, Game_Grid, Player_Movement, Game_People, Game_Canvas, Menu_Canvas, Grid_Entry, Power_Entry, People_Entry, Grid_Rectangle
if Game_Options == "DEFAULT":
Game_Grid = 10
Grid_Rectangle = 600/10
Player_Movement = Grid_Rectangle/2
Player_Power = 150
Game_People = 3
else:
Game_Grid = Grid_Entry.get()
Grid_Rectangle = 600/Game_Grid
Player_Movement = Grid_Rectangle/2
Player_Power = Power_Entry.get()
Game_People = People_Entry.get()
Menu_Canvas.destroy()
Playing_Game = True
Game_Paused = False
Restart_Game = False
Movement_Values = {'w':(1000, 30, 0, -60, -10), 'a':(30, 1000, -60, 0, -1), 's':(1000, 570, 0, 60, 10), 'd':(570, 1000, 60, 0, 1)}
Power_Values = {'#009446':2, '#D4F0FF':1, '#5f6365':3}
People_Locations = {0:[150, 450, 0], 1:[270, 330, 1], 2:[450, 90, 2]}
while Playing_Game == True:
Restart_Game = False
while Restart_Game == False:
if Playing_Game == False:
break
else:
Root = Tk()
Game_Canvas = Canvas(Root, width = 600, height = 600, bd=0, highlightthickness=0)
Generate_Game()
Root.bind('<KeyPress>', Move_Player)
Root.protocol("WM_DELETE_WINDOW", lambda: Game_End("EXIT"))
if Playing_Game == False:
break
Root = Tk()
Start_Game()
Root.mainloop()
Had a look today and it turns out the loops at the bottom were what caused the issue not 100% sure what I did as it was trial and error but I will post the code anyway.
Also that code isn't finished completely yet.
from tkinter import *
from random import choice, shuffle
def Ending_Conditions():
global Player_Power, Players_Collected
if Players_Collected == 3:
Game_End("YOU WIN!")
elif Player_Power <= 0 and Players_Collected != 3:
Game_End("Game Over")
def Game_End(End_Option):
global Playing_Game, Game_Finished
if End_Option == "EXIT":
Playing_Game = False
Root.destroy()
else:
Game_Finished = True
Game_Canvas.create_rectangle(120, 120, 480, 300, fill = "#ffffff")
Game_Canvas.create_text(300, 210, text = End_Option, font = ('Abadi', 35, "bold"))
Continue_Button = Button(Root, text = 'Continue', command = Game_Restart)
Exit_Button = Button(Root, text = 'Exit', command = lambda: Game_End('EXIT'))
Continue_Button.pack()
Exit_Button.pack()
def Game_Restart():
global Already_Played
Root.destroy()
Restart_Game = True
Already_Played = True
def Paused_UI():
global Game_Paused, Close_PausedUI
Close_PausedUI = Button(Root, text = 'Exit', command = Close_Paused_UI)
Close_PausedUI.pack()
Game_Paused = True
def Close_Paused_UI():
global Game_Paused, Close_PausedUI
Close_PausedUI.pack_forget()
Game_Paused = False
def Generate_Game():
global Game_Canvas, Game_Player, Game_Base, Player_Power, Power_Counter, People_Locations, Game_Paused, All_People, Game_Gridcount, Current_Colour, Player_PosY, Player_PosX, Grid_Colour, Players_Collected, Player_Storage
Current_Colour = 0
Grid_Colour = []
Player_PosX, Player_PosY, Player_Storage, Players_Collected, Players_Removed = 300/Game_Gridcount, 300/Game_Gridcount, 0, 0, 0
People_Locations = {0:[150, 450, 0], 1:[270, 330, 1], 2:[450, 90, 2]}
Game_Finished = False
# Generate UI
Game_Menu = Button(Root, text = 'Menu', command = Paused_UI)
Game_Menu.pack()
# Define grid colours
Grid_Colours = ['#009446', '#D4F0FF', '#5f6365']
# Generate power counter and pack canvas
Power_Counter = Label(Root, text = Player_Power)
Power_Counter.pack()
Game_Canvas.pack()
# Generate Grid and Colours
for y in range(Game_Gridcount):
for x in range(Game_Gridcount):
shuffle(Grid_Colours)
Game_Grid = Game_Canvas.create_rectangle(Grid_Rectangle*x, Grid_Rectangle*y, Grid_Rectangle+Grid_Rectangle*x, Grid_Rectangle+Grid_Rectangle*y, fill = Grid_Colours[0])
Grid_Colour.append(Grid_Colours[0])
# Generate Robot Player
Game_Player = Game_Canvas.create_text(Player_PosX, Player_PosY, text = "R", font = ('Abadi', 450//Game_Gridcount, "bold"))
# Generate Player Base
Game_BaseX, Game_BaseY = Grid_Rectangle*(Game_Gridcount-1.5), Grid_Rectangle*(Game_Gridcount-2.5)
Game_Base = Game_Canvas.create_text(Game_BaseX, Game_BaseY, text = "B", font = ('Abadi', 450//Game_Gridcount, "bold"))
# Generate People
for i in range(Game_People):
Person_Location = People_Locations[i] Grid_Rectangle*(Game_Gridcount-1.5)
Game_Person = Game_Canvas.create_text(Grid_Rectangle*(Game_Gridcount-Person_Location[0]), (Grid_Rectangle*(Game_Gridcount-Person_Location[1]), text = "P", font = ('Abadi', 450//Game_Gridcount, "bold"), tag = 'Game_Person')
All_People = Game_Canvas.find_withtag('Game_Person')
All_People = list(All_People)
def Move_Player(event):
global Game_Canvas, Game_Player, Game_Base, Player_PosY, Player_PosX, Current_Colour, Player_Power, Power_Counter, Player_Storage, Players_Collected, Game_Finished, Current_Person
if event.char.lower() == '\x1b' and Game_Paused == False:
Paused_UI()
elif event.char.lower() == '\x1b' and Game_Paused == True:
Close_Paused_UI()
if Game_Paused == False and Game_Finished != True:
Movement_Value = Movement_Values[event.char.lower()]
if Player_PosX != Movement_Value[0] and Player_PosY != Movement_Value[1]:
# Detect current grid colour and configure power accordingly
Player_Power = Player_Power - Power_Values[Grid_Colour[Current_Colour]]
Power_Counter.configure(text = Player_Power)
Current_Colour = Current_Colour + Movement_Value[4]
# Delete the player then recreate in its new position
Game_Canvas.delete(Game_Player)
Player_PosX, Player_PosY = Player_PosX + Movement_Value[2], Player_PosY + Movement_Value[3]
Game_Player = Game_Canvas.create_text(Player_PosX, Player_PosY, text = "R", font = ('Abadi', 450//Game_Gridcount, "bold"))
# Detect Person
for item in People_Locations:
Person_Location = People_Locations[item]
if Player_PosX == Person_Location[0] and Player_PosY == Person_Location[1] and Player_Storage != 1:
Current_Person = Person_Location[2]
Game_Canvas.delete(All_People[Current_Person])
Player_Storage += 1
if Player_PosX == 450 and Player_PosY == 330:
if Player_Storage == 1:
Player_Storage -= 1
Players_Collected += 1
Clear_Current = People_Locations[Current_Person]
Clear_Current = Clear_Current[2]
People_Locations.pop(Clear_Current)
Ending_Conditions()
def Start_Game():
global Start_Canvas
Start_Canvas = Canvas(Root, width = 600, height = 500, bd=0, highlightthickness=0, bg = '#ffffff')
Start_Canvas.pack()
Title = Start_Canvas.create_text(300, 163, text = "BOTMOD", font = ('Cinema Gothic BTN Shadow', 75, 'normal'))
Play_Button = Button(text = "PLAY", width = 10, font=('Arial', 15), command = Play_Game)
Play_Button = Start_Canvas.create_window(300, 325, window = Play_Button)
Exit_Button = Button(text = "EXIT", width = 10, font=('Arial', 15), command = lambda: Game_End("EXIT"))
Exit_Button = Start_Canvas.create_window(300, 375, window = Exit_Button)
def Play_Game():
global Menu_Canvas, Grid_Entry, Power_Entry, People_Entry
if Already_Played == False:
Start_Canvas.destroy()
Menu_Canvas = Canvas(Root, width = 600, height = 500, bd=0, highlightthickness=0, bg = '#C0C0C0')
Menu_Canvas.pack()
Title_Rectangle = Menu_Canvas.create_rectangle(120, 10, 480, 100, fill = '#000000')
Slider_Rectangle = Menu_Canvas.create_rectangle(120, 110, 480, 430, fill = '#000000')
Footer_Rectangle = Menu_Canvas.create_rectangle(120, 440, 480, 490, fill = '#000000')
Title = Menu_Canvas.create_text(300, 55, text = "BOTMOD", font = ('Cinema Gothic BTN Shadow', 55, 'normal'), fill = '#ffffff')
Description_Text = Label(text = "Set Game Options", font=('Arial', 15, 'bold'), bg = '#000000', fg = '#ffffff')
Description_Text = Menu_Canvas.create_window(300, 145, window = Description_Text)
Power_Text = Label(text = "Robot Power", font=('Cinema Gothic BTN Shadow', 15), bg = '#000000', fg = '#ffffff')
Power_Text = Menu_Canvas.create_window(300, 195, window = Power_Text)
Power_Entry = Scale(Root, from_= 50, to = 350, orient = HORIZONTAL, bg = '#000000', fg = '#ffffff', highlightthickness=0, bd = 0)
Power_Entrys = Menu_Canvas.create_window(300, 225, window = Power_Entry)
People_Text = Label(text = "Person Count", font=('Cinema Gothic BTN Shadow', 15), bg = '#000000', fg = '#ffffff')
People_Text = Menu_Canvas.create_window(300, 280, window = People_Text)
People_Entry = Scale(Root, from_= 2, to = 10, orient = HORIZONTAL, bg = '#000000', fg = '#ffffff', highlightthickness=0, bd = 0)
People_Entrys = Menu_Canvas.create_window(300, 310, window = People_Entry)
Grid_Text = Label(text = "Grid Count", font=('Cinema Gothic BTN Shadow', 15), bg = '#000000', fg = '#ffffff')
Grid_Text = Menu_Canvas.create_window(300, 365, window = Grid_Text)
Grid_Entry = Scale(Root, from_= 6, to = 14, orient = HORIZONTAL, resolution = 2, bg = '#000000', fg = '#ffffff', highlightthickness=0, bd = 0)
Grid_Entrys = Menu_Canvas.create_window(300, 395, window = Grid_Entry)
Play_Button = Button(text = "OK", width = 15, font=('Cinema Gothic BTN Shadow', 10), command = lambda: Init_Game("CUSTOM"), bg = '#000000', fg = '#ffffff')
Play_Button = Menu_Canvas.create_window(400, 465, window = Play_Button)
PlayWD_Button = Button(text = "Use Defaults", width = 15, font=('Cinema Gothic BTN Shadow', 10), command = lambda: Init_Game("DEFAULT"), bg = '#000000', fg = '#ffffff')
PlayWD_Button = Menu_Canvas.create_window(200, 465, window = PlayWD_Button)
def Init_Game(Game_Options):
global Player_PosY, Player_PosX, Game_Paused, Game_Finished, Playing_Game, Player_Power, Game_Gridcount, Player_Movement, Game_People, Game_Canvas, Movement_Values, Power_Values, Grid_Rectangle
if Game_Options == "DEFAULT":
Game_Gridcount = 10
Grid_Rectangle = 600/10
Player_Movement = Grid_Rectangle/2
Player_Power = 150
Game_People = 3
elif Game_Options == "CUSTOM":
Game_Gridcount = Grid_Entry.get()
Grid_Rectangle = 600/Game_Gridcount
Player_Movement = Grid_Rectangle/2
Player_Power = Power_Entry.get()
Game_People = People_Entry.get()
Movement_Values = {'w':(1000, 300/Game_Gridcount, 0, -600/Game_Gridcount, 10), 'a':(300/Game_Gridcount, 1000, -600/Game_Gridcount, 0, -1), 's':(1000, 600-Player_Movement, 0, 600/Game_Gridcount, Game_Gridcount-Game_Gridcount*2), 'd':(600-Player_Movement, 1000, 600/Game_Gridcount, 0, 1)}
Power_Values = {'#009446':2, '#D4F0FF':1, '#5f6365':3}
People_Locations = {0:[1.5, 1.5, 0], 1:[1.5, 4.5, 1], 2:[1.5, 1.5, 2], 3:[1.5, 1.5, 3], 4:[1.5, 1.5, 4], 5:[1.5, 1.5, 5], 6:[1.5, 1.5, 6], 7:[1.5, 1.5, 7], 8:[1.5, 1.5, 8], 9:[1.5, 1.5, 9], 10:[1.5, 1.5, 10]}
Menu_Canvas.destroy()
Game_Canvas = Canvas(Root, width = 600, height = 600, bd=0, highlightthickness=0)
Generate_Game()
Root.bind('<KeyPress>', Move_Player)
Root.protocol("WM_DELETE_WINDOW", lambda: Game_End("EXIT"))
Playing_Game = True
Game_Paused = False
Restart_Game = False
Already_Played = False
while True:
while Restart_Game == False:
if Playing_Game == False:
break
else:
Game_Finished = False
Grid_Colour = []
Power_Values = {'#009446':2, '#D4F0FF':1, '#5f6365':3}
Root = Tk()
if Already_Played == True:
Play_Game()
Root.mainloop()
elif Already_Played == False:
Start_Game()
Root.mainloop()
break