AttributeError: 'StringVar' object has no attribute 'tk' - python-3.x

I'm trying to limit characters, but I got this error and I have no idea how to get out, I'm not very experienced in python, I caught up shortly in language.
And already enjoying the crash wanted to know how I do to limit a user to register with the same user. Example:
It has been registered "A", and in the next one I will not be able to register it anymore
from tkinter import *
from tkinter import ttk
import tkinter as tk
class loginUser:
def __init__(self, window, master=None):
self.wind = window
self.wind.title("System F2T")
#Definicoes de fonte p/ o layout de login
self.fonteTitulo = ("Arial","10","bold")
self.fontePadrao = ("Arial", "10")
self.var = tk.StringVar()
self.var2 = tk.StringVar()
self.userLabel = Label(text="Digite seu usuário:", font=self.fontePadrao,bg="#000",fg="#FFF").place(x=27,y=60)
self.user = Entry(textvariable=self.var, font=self.fontePadrao,bg="#FFF",fg="#000")
self.user.place(x=140,y=60,width=110)
self.senhaLabel = Label(text="Digite sua senha:", font=self.fontePadrao,bg="#000",fg="#FFF").place(x=29,y=90)
self.senha = Entry(self.var2, font=self.fontePadrao,show="*",bg="#FFF",fg="#000")
self.senha.place(x=140,y=90,width=110)
def limiteUsuario(self,*args):
u = self.var.get()
if len(u) == 1 and not 65<=ord(u)<=68: # you can also use *if not u in "ABCD"*
self.var.set("")
elif len(u) > 1:
if not 65<=ord(u[-1])<=68: # retirar ultimo caracter caso nao seja digito
self.var.set(u[:-1])
else: # aproveitar apenas os primeiros 5 chars
self.var.set(u[:self.max_user])
def limiteSenha(self,*args):
s = self.var2.get()
if len(s) > 4:
if not s[-1].isdigit(): # retirar ultimo caracter caso nao seja digito
self.var2.set(s[:-1])
else: # aproveitar apenas os primeiros 5 chars
self.var2.set(s[:self.max_senha])
if __name__ == "__main__":
root = Tk()
root['bg'] = "#000"
loginUser(root)
#Tamanho da janela
root.geometry("330x200")
root.mainloop()

Related

How can I put this script in a function?

I want to display a text first and remove it after a second, and keep the software running during this time (that is, preventing the loop) and getting the text and display it repeatedly.
I want this to be in the form of a function
I want to display the text with each key and the text operation is in a function
import keyboard
import pynput
import tkinter, win32api, win32con, pywintypes
def printer(text):
label = tkinter.Label(text=text, font=('Times New Roman','16'), fg='white', bg='blue')
label.master.overrideredirect(True)
label.master.geometry("+0+0")
label.master.lift()
label.master.wm_attributes("-topmost", True)
label.master.wm_attributes("-disabled", True)
label.master.wm_attributes("-transparentcolor", "blue")
hWindow = pywintypes.HANDLE(int(label.master.frame(), 16))
exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle)
label.pack()
label.after(1000, lambda:label.config(text=''))
label.mainloop()
pressedList = ''
def on_press(key):
global pressedList
try:
pressedKey = key.char # single-char keys
except:
pressedKey = key.name # other keys
pressedList += pressedKey
if pressedList.rfind('a')+len('a') == len(pressedList) and pressedList[pressedList.rfind('a'):] == 'a':
printer('a')
elif pressedList.rfind('f1')+len('f1') == len(pressedList) and pressedList[pressedList.rfind('f1'):] == 'f1' and pressedKey == 'f1':
printer('f1')
else:
printer('pass')
pass
lis = pynput.keyboard.Listener(on_press=on_press)
lis.start()
lis.join()
You probably do not need to mix tkinter with other events listeners; binding a keypress to a tkinter window will do what you require:
import tkinter as tk
def display_key(e=None):
if e is not None:
tv.set(e.keysym)
root.after(1000, display_key)
else:
tv.set('-')
root = tk.Tk()
root.geometry('300x200')
tv = tk.StringVar()
tv.set('-')
label = tk.Label(root, textvariable=tv)
label.config(font=("Courier", 144))
label.pack(expand=True, fill='both')
root.bind('<Key>', display_key)
root.mainloop()

print but not setText

in my problem I have 2 windows. I'm putting entries in a table in the first one and I would like to display it in the second one. There is 2 column in the table. The first one is used for the combobox in window2. The second one is the one I would like to display (if row 1 is selected in combobox, print row 1 (column 2) if row 2 is selectd in combobox, print row 2 (column 2))
I don't have any error message or anything, I can print the right text, but somehow, I can't label il (settext) Any idea of my mistake ?
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import QTableWidgetItem, QComboBox
from PyQt5.QtWidgets import QApplication, QPushButton, QDialog, QGroupBox,QVBoxLayout, QGridLayout, QLabel, QTableWidget, QScrollArea
class Window(QDialog):
def __init__(self):
super().__init__()
self.title = "XXXX"
self.top = 50
self.left = 50
self.width = 1250
self.height = 650
self.setStyleSheet("background-color:white")
self.InitWindow()
def InitWindow(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
groupBox = QGroupBox()
gridLayout = QGridLayout()
#TABLEAU
Window.table10 = QTableWidget(self)
Window.table10.setRowCount(3) # set row count
Window.table10.setColumnCount(2) # set column count
Window.table10.setMaximumHeight(250)
#entête
Window.table10.setItem(0,0, QTableWidgetItem("Equipement"))
Window.table10.setItem(0,1, QTableWidgetItem("Value"))
gridLayout.addWidget(Window.table10, 1 , 2 , 3, 6)
button11 = QPushButton("générer le profil de charge",self)
button11.setStyleSheet("background-color:rgb(2,154,132); color: white")
button11.setMinimumHeight(20)
button11.setMinimumWidth(80)
button11.clicked.connect(self.charge)
gridLayout.addWidget(button11, 5 , 1)
groupBox.setLayout(gridLayout)
scroll = QScrollArea()
scroll.setWidget(groupBox)
scroll.setWidgetResizable(True)
vbox = QVBoxLayout()
vbox.addWidget(scroll)
self.setLayout(vbox)
self.show()
def charge(self):
"""Lance la 2ème fenêtre en cas de clic sur le bouton
"""
# crée la 2ème fenêtre
self.profilcharge = ProfilCharge()
# rend modale la 2ème fenêtre (la 1ère fenêtre sera inactive)
self.profilcharge.setWindowModality(QtCore.Qt.ApplicationModal)
# affiche la 2ème fenêtre
self.profilcharge.show()
class ProfilCharge(Window):
# crée un signal pour envoyer une chaine à la fermeture de la fenêtre
fermetureprofilcharge = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
super().__init__()
self.title = "profil de charge"
self.top = 50
self.left = 50
self.width = 300
self.height = 400
self.InitWindow()
def InitWindow(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
groupBox = QGroupBox()
self.gridLayout = QGridLayout()
self.label1 = QLabel("chose an equipment",self)
self.gridLayout.addWidget(self.label1, 2 , 1)
self.combo = QComboBox()
i=1
while (i<Window.table10.rowCount()):
self.combo.addItem(str(Window.table10.item(i,0).text()),i)
i=i+1
self.gridLayout.addWidget(self.combo, 0 , 1 )
self.combo.activated[str].connect(self.nbheures)
groupBox.setLayout(self.gridLayout)
scroll = QScrollArea()
scroll.setWidget(groupBox)
scroll.setWidgetResizable(True)
vbox = QVBoxLayout()
vbox.addWidget(scroll)
self.setLayout(vbox)
self.show()
def nbheures(self,text):
for i in range(Window.table10.rowCount()):
if text == str(Window.table10.item(i,0).text()):
value=str(Window.table10.item(i,1).text())
break
print(value)
self.label1.setText(value)
if __name__ =="__main__":
App = QApplication(sys.argv)
App.aboutToQuit.connect(App.deleteLater)
window = Window()
App.exec()
You are calling self.InitWindow() twice (one in Window.__init__, one in ProfilCharge.__init__). The second time, you try to set a new layout to widget which already has one and the operation is discarded.
The current value of self.label1 is changed the second time. But, as you still see the first instance of your label, you will not see any changes.
ProfilCharge should not inherit from Window.

AttributeError: 'loginUser' object has no attribute 'var'

I am trying to limit characters, but I find this error. Someone to help?
And would it be able to limit characters from type A to D and from 0 to 9?
In the initializer I already got it, now I want to try out the initializer, but I could not understand this error, I'm new at it.
class loginUser:
def __init__(self, window, master=None):
self.wind = window
self.wind.title("System F2T")
#Definicoes de fonte p/ o layout de login
self.fonteTitulo = ("Arial","10","bold")
self.fontePadrao = ("Arial", "10")
#Labels e campos de texto do sistema de login
self.userLabel = Label(text="Digite seu usuário:", font=self.fontePadrao,bg="#000",fg="#FFF").place(x=27,y=60)
self.user = Entry(textvariable=self.var, font=self.fontePadrao,bg="#FFF",fg="#000")
self.user.place(x=140,y=60,width=110)
self.senhaLabel = Label(text="Digite sua senha:", font=self.fontePadrao,bg="#000",fg="#FFF").place(x=29,y=90)
self.senha = Entry(textvariable=self.var2, font=self.fontePadrao,show="*",bg="#FFF",fg="#000")
self.senha.place(x=140,y=90,width=110)
self.max_user = 1
self.var = StringVar()
self.var.trace("w", loginUser.limiteUsuario)
self.max_senha = 4
self.var2 = StringVar()
self.var2.trace("w", loginUser.limiteSenha)
def limiteUsuario(self,*args):
u = self.var.get()
if len(u) == 1 and not 65<=ord(u)<=68: # you can also use *if not u in "ABCD"*
self.var.set("")
elif len(u) > 1:
if not 65<=ord(u[-1])<=68: # retirar ultimo caracter caso nao seja digito
self.var.set(u[:-1])
else: # aproveitar apenas os primeiros 5 chars
self.var.set(u[:self.max_user])
def limiteSenha(self,*args):
s = self.var2.get()
if len(s) > 4:
if not s[-1].isdigit(): # retirar ultimo caracter caso nao seja digito
self.var2.set(s[:-1])
else: # aproveitar apenas os primeiros 5 chars
self.var2.set(s[:self.max_senha])
if __name__ == "__main__":
root = Tk()
root['bg'] = "#000"
loginUser(root)
#Tamanho da janela
root.geometry("330x200")
root.mainloop()
As Bryan pointed out, your self.var is being set as a text variable before it has been created. Simply shuffle where you defined them to fix.
class loginUser:
def __init__(self, window, master=None):
self.wind = window
self.wind.title("System F2T")
...
self.var = StringVar() #create the var first before you assign them
self.var2 = StringVar()
#Labels e campos de texto do sistema de login
self.user = Entry(textvariable=self.var, font=self.fontePadrao,bg="#FFF",fg="#000")
...
self.senha = Entry(textvariable=self.var2, font=self.fontePadrao,show="*",bg="#FFF",fg="#000")
On how to limit your the input from A-D, you can add an additional check in your limiteUsuario method. Note that I also fixed the potential errors from your class method.
def limiteUsuario(self,*args):
u = self.var.get()
if len(u) == 1 and not 65<=ord(u)<=68: # you can also use *if not u in "ABCD"*
self.var.set("")
elif len(u) > 1:
if not 65<=ord(u[-1])<=68: # retirar ultimo caracter caso nao seja digito
self.var.set(u[:-1])
else: # aproveitar apenas os primeiros 5 chars
self.var.set(u[:self.max_user])
You can use the similar logic for number 0-9.

What's the pythonic way to make working a socket client with tkinter?

I'm trying to set up a GUI/TCP client that displays some received data from a TCP server in Python. To do so, I'm using tkinter module.
I have 2 questions about the code I post below:
How do I implement this in a pythonic way?
How do I use threading join() to wait having a filled self.inboundMessage before continue the Application execution?
( * In comments some of the things I've tried )
import tkinter as tk
from tkinter import *
from tkinter import ttk
import socket
import threading
from threading import *
import json # Import json module
import logging # Import logging module
import random
import time
logging.basicConfig(level=logging.DEBUG, format='[%(threadName)-10s] %(message)s',)
class MyLabel(tk.Label):
def __init__(self, root, func, **kwargs):
tk.Label.__init__(self, root, **kwargs)
self.func = func
self.update()
def update(self):
self.configure(text=str(self.func()))
self.after(500, self.update)
# To be implemented as an interface
class MyFrame(ttk.Frame):
def __init__(self, root):
super().__init__(root)
def read(self):
pass
def write(self):
pass
def update(self):
pass
class MyInfoFrame(MyFrame):
def __init__(self, root, func):
super().__init__(root)
dictionary = func()
self.func = func
self.values = {}
row = 0
###############
print('**************')
print(dictionary)
##############
try:
for sensor in dictionary['sensor']:
tk.Label(self, text = sensor['name']).grid(row=row, column=0)
self.values[sensor['name']] = tk.Label(self, text = sensor['value'], relief=SUNKEN, width=5)
self.values[sensor['name']].grid(row=row, column=1)
tk.Label(self, text = sensor['unit']).grid(row=row, column=2)
row = row + 1
for handler in dictionary['handler']:
tk.Label(self, text = handler['name']).grid(row=row, column=0)
self.values[handler['name']] = tk.Label(self, text = handler['status'], relief=SUNKEN, width=5)
self.values[handler['name']].grid(row=row,column=1)
row = row + 1
except:
print('MyInfoFrame.__init__ reading error...')
pass
self.update()
def update(self):
dictionary = self.func()
try:
#################
print('\n **************')
print(dictionary['sensor'])
print('**************\n')
#################
for sensor in dictionary['sensor']:
self.values[sensor['name']].configure(text=sensor['value'])
for handler in dictionary['handler']:
self.values[handler['name']].configure(text=handler['status'])
except:
#print('MyInfoFrame.update reading error...')
logging.error('MyInfoFrame.update reading error...')
pass
self.after(500, self.update)
class MySettingsFrame(MyFrame):
def __init__(self, root, **kwargs):
super().__init__(root)
self.systemOn = False
self.getOutboundMessage = kwargs['func_2']
self.outboundMessage = self.getOutboundMessage()
tk.Label(self, text='Encendido').grid(row=0,column=0)
ttk.Radiobutton(self, text='ON', value='ON', command=self.setSystemOn).grid(row=0,column=1)
offButton = ttk.Radiobutton(self, text='OFF', value='OFF', command=self.setSystemOff)
offButton.grid(row=0,column=2)
offButton.invoke()
self.scaleValue = 15.0
self.scale = ttk.Scale(self, orient=HORIZONTAL, length=200, from_=self.scaleValue, to=35.0, command=self.setScaleValue)
self.scale.set(self.scaleValue)
self.scale.grid(row=2,column=1)
tk.Label(self, text='Temp. Consigna').grid(row=1,column=0)
MyLabel(self, func=self.getScaleValue, relief=SUNKEN, width=5).grid(row=1,column=1)
tk.Label(self, text='ºC').grid(row=1,column=2)
self.update()
def setSystemOn(self):
self.systemOn = True
def setSystemOff(self):
self.systemOn = False
def setScaleValue(self, *args):
self.scaleValue = round(self.scale.get(), 1)
def getScaleValue(self):
return self.scaleValue
def write(self):
self.outboundMessage['timestamp'] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
self.outboundMessage['origin'] = 'front-end'
self.outboundMessage['action'] = 'set'
self.outboundMessage['setup'] = self.scaleValue
if self.systemOn:
self.outboundMessage['system'] = 'ON'
else:
self.outboundMessage['system'] = 'OFF'
def update(self):
self.write()
self.after(500, self.update)
class MyAdvancedFrame(MyFrame):
def __init__(self, root, **kwargs):
super().__init__(root)
self.tempIntSimulated = False
self.tempExtSimulated = False
self.getInboundMessage = kwargs['func_1']
self.getOutboundMessage = kwargs['func_2']
self.tempInt = self.getInboundMessage()['sensor'][0]['value']
self.tempExt = self.getInboundMessage()['sensor'][1]['value']
self.bridgeVar = StringVar()
tk.Label(self, text='Marcha/Paro').grid(row=0,column=0)
self.bridge_button_on = ttk.Radiobutton(self, text='ON', value='ON', variable=self.bridgeVar, command=self.setBridge)
self.bridge_button_on.grid(row=0,column=1)
self.bridge_button_off = ttk.Radiobutton(self, text='OFF', value='OFF', variable=self.bridgeVar, command=self.setBridge)
self.bridge_button_off.grid(row=0,column=2)
self.bridge_button_auto = ttk.Radiobutton(self, text='AUTO', value='AUTO', variable=self.bridgeVar, command=self.setBridge)
self.bridge_button_auto.grid(row=0,column=3)
self.bridge_button_auto.invoke()
tk.Label(self, text='Temp. Interior').grid(row=1,column=0)
self.t_int_label = MyLabel(self, func=self.getTempInt, relief=SUNKEN, width=5)
self.t_int_label.grid(row=1,column=1)
self.tempInt = StringVar()
self.temp_int_entry = ttk.Entry(self, textvariable=self.tempInt, width=5)
self.temp_int_entry.grid(row=1,column=2)
#temp_int_entry.config(state='disabled')
self.t_int_checkbutton = tk.Checkbutton(self, text='Simulado', command=self.setTempIntSimulated)
self.t_int_checkbutton.grid(row=1,column=3)
tk.Label(self, text='Temp. Exterior').grid(row=2,column=0)
MyLabel(self, func=self.getTempExt, relief=SUNKEN, width=5).grid(row=2,column=1)
self.tempExt = StringVar()
temp_ext_entry = ttk.Entry(self, textvariable=self.tempExt, width=5)
temp_ext_entry.grid(row=2,column=2)
self.t_ext_checkbutton = tk.Checkbutton(self, text='Simulado', command=self.setTempExtSimulated)
self.t_ext_checkbutton.grid(row=2,column=3)
self.update()
def setBridge(self):
outboundMessage = self.getOutboundMessage()
outboundMessage['forced']['bridge'] = self.bridgeVar.get()
def setTempIntSimulated(self):
if self.tempIntSimulated:
self.tempIntSimulated = False
self.temp_int_entry.config(state='normal')
#self.temp_int_entry.delete(0, END)
outboundMessage = self.getOutboundMessage()
outboundMessage['forced']['int'] = ''
else:
self.tempIntSimulated = True
outboundMessage = self.getOutboundMessage()
outboundMessage['forced']['int'] = self.tempInt.get()
self.temp_int_entry.config(state='disabled')
def setTempExtSimulated(self):
if self.tempExtSimulated:
self.tempExtSimulated = False
else:
self.tempExtSimulated = True
outboundMessage = self.getOutboundMessage()
outboundMessage['forced']['ext'] = self.tempExt.get()
def update(self):
self.readTempInt()
self.readTempExt()
self.after(500, self.update)
def readTempInt(self):
inboundMessage = self.getInboundMessage()
try:
self.tempInt = inboundMessage['sensor'][0]['value']
except:
pass
def readTempExt(self):
inboundMessage = self.getInboundMessage()
try:
self.tempExt = inboundMessage['sensor'][1]['value']
except:
pass
def getTempInt(self):
return self.tempInt
def getTempExt(self):
return self.tempExt
class Application(ttk.Frame): #, socket.socket):
def __init__(self, main_window, targetServer, bufferSizeMsg):
ttk.Frame.__init__(self, main_window) # Iniciando clase como Frame
#socket.socket.__init__(self, socket.AF_INET, socket.SOCK_STREAM) # Iniciando clase como socket
self.socket = None
# Parametros de comunicacion con el servidor
self.targetServer = targetServer
self.bufferSizeMsg = bufferSizeMsg
main_window.title("GRUPO A3I - Panel de control")
# Mensaje entrante desde el backend
self.inboundMessage = {}
# Mensage saliente. Settea consignas y valores forzados. Se envía al backend
self.outboundMessage = {'origin':'front-end', 'action':'none', 'forced':{'bridge':'AUTO','int':'','ext':''}}
# Threading la comunicación como cliente con el backend (servidor)
'''
self.thread = threading.Thread(target=self.communicate)
self.thread.daemon = True
self.thread.start()
'''
self.createCommThread()
while self.inboundMessage == {}:
pass
#time.sleep(1)
############
#self.thread = threading.Thread(target=self.communicate)
#self.thread.daemon = False #True
#self.thread.start()
#self.thread.join()
#############
# Crear el panel de pestañas.
self.notebook = ttk.Notebook(self)
# Crear el contenido de cada una de las pestañas.
self.frame_info = MyInfoFrame(self, func=self.getInboundMessage)
self.frame_settings = MySettingsFrame(self, func_2=self.getOutboundMessage)
self.frame_advanced = MyAdvancedFrame(self, func_1=self.getInboundMessage, func_2=self.getOutboundMessage)
# Añadirlas al panel con su respectivo texto.
self.notebook.add(self.frame_info, text="Info", padding=20)
self.notebook.add(self.frame_settings, text="Settings", padding=20)
self.notebook.add(self.frame_advanced, text="Avanzado", padding=20)
# Margenes
self.notebook.pack(padx=10, pady=10)
self.pack()
def __del__(self):
if self.socket != None:
self.socket.close()
def getInboundMessage(self):
return self.inboundMessage
def getOutboundMessage(self):
return self.outboundMessage
def setOutboundMessage(self, outboundMessage):
self.outboundMessage = outboundMessage
def createCommThread(self):
self.thread = threading.Thread(target=self.communicate)
self.thread.daemon = False #True
self.thread.start()
#self.thread.join()
def communicate(self):
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
logging.debug('Connecting to %s', self.targetServer)
self.socket.connect(self.targetServer)
logging.debug('Sending message %s', self.outboundMessage) self.socket.sendall(json.dumps(self.outboundMessage).encode('utf-8'))
inboundMessage = self.socket.recv(self.bufferSizeMsg)
logging.debug('Inbound Message %s', inboundMessage)
self.inboundMessage = json.loads(inboundMessage)
#self.close()
except socket.timeout as errorTimeoutMsg:
time.sleep(2)
print(errorTimeoutMsg)
#input("Socket Timeout...")
except socket.gaierror as errorGaiMsg:
time.sleep(2)
print(errorGaiMsg)
#input("Socket Gaierror")
except socket.error as errorMsg:
time.sleep(2)
print(errorMsg)
#input("Socket Error...")
finally:
self.socket.close()
#self.after(2000, self.communicate)
self.after(500, self.createCommThread)
#self.after(2000, self.communicate)
main_window = tk.Tk()
targetServer = ('raspberrypi.local', 5005)
bufferSizeMsg = 2048
app = Application(main_window, targetServer, bufferSizeMsg)
app.mainloop()
Error
If the TCP server is not running, I'm getting the following error message:
RuntimeError: main thread is not in main loop

Tkinter Label and Entry

I plan a mathematical game. I want the randint from label 1 + randint from label 2 to be calculated and then check if my entry is the same as the calculated number.
I want to add z1 to z2 and check if the Entry is the same but I don't know how I can add one random number to the other.
I can't add z1 to z2 so what is the way to do that? Should this happen in the if...else?
from tkinter import *
from random import *
fenster = Tk()
fenster.title("Mathe-Spiel")
fenster.geometry("300x300")
def anfang():
z1 =label = Label(fenster, text=(randint(1,100)))
label.pack()
zp=label2 = Label(fenster, text="+")
label2.pack()
z2= label1 = Label(fenster, text=(randint(1,100)))
label1.pack()
a =label3 = Label(fenster,)
label3.pack()
e1=eingabe = Entry(fenster)
eingabe.pack()
e2=z1+z2
def ausgabe():
if (e1==e2):
a.configure(text=(eingabe.get()))
else:
a.configure(text="Falsch")
ergebnis = Button(fenster, text="ergebnis", command= ausgabe)
ergebnis.pack()
anfangsknopf = Button(fenster, text="Fange mit dem Spielen an", command=anfang)
anfangsknopf.pack()
mainloop()
Error: You are trying adding 2 labels together (e2=z1+z2) but you expect that you add the values in your z1 and z2 text option!
You can get the right values while get text from z1 and z2 but I would do it in a different way.
like so:
from tkinter import Tk, IntVar, Button, Label, Entry
from random import randint
class Gui:
def __init__(self, master):
self.master = master
self.summand1 = IntVar()
self.summand2 = IntVar()
anfangsknopf = Button(self.master, text="Fange mit dem Spielen an", command=self.create_widgets)
anfangsknopf.pack()
def create_widgets(self):
""" create widgets on the fly """
try:
self.label1.destroy()
self.label2.destroy()
self.label3.destroy()
self.eingabe.destroy()
self.ergebnis.destroy()
self.answer.destroy()
except:
print("No widgets destroyed")
self.fill_summands()
self.label1 = Label(self.master, textvariable=self.summand1)
self.label2 = Label(self.master, text="+")
self.label3 = Label(self.master, textvariable=self.summand2)
self.eingabe = Entry(self.master)
self.ergebnis = Button(self.master, text="ergebnis", command= self.ausgabe)
self.answer = Label(self.master, text="...")
self.label1.pack()
self.label2.pack()
self.label3.pack()
self.eingabe.pack()
self.ergebnis.pack()
self.answer.pack()
self.eingabe.focus_set()
def get_random_nr(self):
""" get random number """
return randint(1,100)
def fill_summands(self):
""" set IntVar variables """
r_number1 = self.get_random_nr()
r_number2 = self.get_random_nr()
self.summand1.set(r_number1)
self.summand2.set(r_number2)
def ausgabe(self):
""" calculate addition """
try:
if self.summand1.get()+self.summand2.get() == int(self.eingabe.get()):
print("Correct")
self.answer.configure(text="Correct", fg="Green")
else:
print("Wrong")
self.answer.configure(text="Wrong", fg="Red")
except ValueError:
print("Please set a number in Entry widget")
self.answer.configure(text="Bitte gültige Nummer eingeben", fg="Red")
if __name__ == "__main__":
fenster = Tk()
fenster.title("Mathe-Spiel")
fenster.geometry("300x300")
app = Gui(fenster)
fenster.mainloop()

Resources