Label does not update on button click - python

We have to make a test for elementary school kids to test there skills in math. I need the label on the left to have a random equation, and the right have an entry form, and the far right to have a button that checks if the answer they gave is correct. If they got it right a new equation is given.
from tkinter import Label, Frame, Entry, Button, LEFT, RIGHT, END, TOP, END
from tkinter.messagebox import showinfo
from random import randrange
class Ed(Frame):
'Simple arithmetic education app'
def __init__(self,parent=None):
'constructor'
Frame.__init__(self, parent)
self.pack()
Ed.new_problem(self)
Ed.make_widgets(self)
self.tries = 0
def make_widgets(self):
'defines Ed widgets'
if self.plusminus == 1:
Label(self, text=(self.a ,"+" ,self.b)).pack(side=LEFT)
else:
Label(self, text=(self.a, "-" ,self.b)).pack(side=LEFT)
self.ent = Entry(self)
self.ent.pack(side=LEFT)
Button(self, text='Enter', command=self.evaluate).pack(side=RIGHT)
def new_problem(self):
'creates new arithmetic problem'
self.a = randrange(1,10,1)
self.b = randrange(1,10,1)
self.c = randrange(1,10,1)
if self.c < 5:
self.total = self.a + self.b
self.plusminus = 1 #plusminus = plus
else:
self.total = self.a - self.b
self.plusminus = 0 #plusminus = minus
def evaluate(self):
'handles button "Enter" clicks by comparing answer in entry to correct result'
if self.total == eval(self.ent.get()):
showinfo(title='YAY', message='You are CORRECT!')
self.ent.delete(0,END)
else:
self.ent.delete(0,END)
self.ent.insert(END, 'Wrong. Try again.')
self.tries+=1
Ed().mainloop()
The problem is the equation does not update when the answer is correct. So when I enter 12 when the question is 8 + 4. It cays correct but keeps 8 + 4 tho I want it to change to a new equation.

You're only calling new_problem when your Ed object is instantiated. It's never called again afterwards, and doing so won't actually change the existing set up, as you only create the labels for your widget once, also at instantiation.
What you need to do is pass in a tkinter.StringVar to your Label widget, and then set the arithmetic problem on that variable. You then run new_problem after each successful answer.
I've updated your code slightly to use super and run methods directly on the instance rather than via the class, but this should work:
from tkinter import Label, Frame, Entry, Button, LEFT, RIGHT, END, TOP, END, StringVar
from tkinter.messagebox import showinfo
from random import randrange
class Ed(Frame):
"""Simple arithmetic education app"""
def __init__(self,parent=None):
"""constructor"""
super().__init__(parent)
self.tries = 0
self.problem = StringVar()
self.make_widgets()
self.new_problem()
self.pack()
def make_widgets(self):
"""defines Ed widgets"""
self.label = Label(self, textvariable=self.problem)
self.label.pack(side=LEFT)
self.ent = Entry(self)
self.ent.pack(side=LEFT)
Button(self, text='Enter', command=self.evaluate).pack(side=RIGHT)
def new_problem(self):
"""creates new arithmetic problem"""
self.tries = 0
self.a = randrange(1,10,1)
self.b = randrange(1,10,1)
if randrange(1,10,1) < 5:
self.total = self.a + self.b
self.plusminus = '+'
else:
self.total = self.a - self.b
self.plusminus = '-'
self.problem.set( (self.a , self.plusminus, self.b) )
def evaluate(self):
"""handles button "Enter" clicks by comparing answer in entry to correct result"""
if self.total == int(self.ent.get()):
showinfo(title='YAY', message='You are CORRECT!')
self.ent.delete(0,END)
self.new_problem()
else:
self.ent.delete(0,END)
self.ent.insert(END, 'Wrong. Try again.')
self.tries += 1
Ed().mainloop()
I've also changed your eval to an int...you really don't want to be doing that, because it enables users to inject python code into your application.
For example, I can type the following as my "answer":
showinfo(title="Blah", message="Look ma - No hands!")
That would just bring up a simple message box, but the door is wide open for more involved mischief.

Related

how do i allow a function to be used anywhere in python tkinter?

i have 2 classes and when i run the first one, it works fine but when it gets to the second class i get an error saying AttributeError: 'Question2' object has no attribute 'correct'. how do i make it so that the functions work in both of the class? is there something wrong with my indent? please help me fix this code, thanks:
Edit: i have a problem with using self, if i remove self from the functions it wouldnt work, if i indent it to not be a part of the class, it still wont work, the self gets turns white
class Question1:
def __init__ (self, master):
x = random.randint(5, 12)
y = random.randint(5, 12)
self.master = master
self.user_choice = StringVar()
self.user_choice.set("")
self.frame = Frame(master, padx=200, pady=200)
self.frame.grid()
self.q = Label(self.frame, text="What is {} + {} ?".format(x, y))
self.q.grid(row=0)
self.ans = Entry(self.frame, width=50, textvariable=self.user_choice)
self.ans.grid(row=1)
self.answer = x+y
self.sub = Button(self.frame, text="submit", command=self.correct)
self.sub.grid(row=3)
def correct(self):
global p
if int(self.user_choice.get()) == self.answer:
cor = Label(self.frame,text="Correct!")
cor.grid(row=5, pady=20)
p += 1
if p >= 3:
Question2(self.master)
else:
self.sub.destroy()
nex = Button(self.frame, text="Next", command=self.necs)
nex.grid(row=4)
else:
inc = Label(self.frame,text="incorrect")
inc.grid(row=5, pady=20)
self.sub.destroy()
nex = Button(self.frame, text="Next", command=self.necs)
nex.grid(row=4)
self.frame.destroy()
Question1(self.master)
def necs(self):
self.frame.destroy()
Question1(self.master)
class Question2:
def __init__(self, master):
x = random.randint(2, 2)
y = random.randint(2, 3)
self.master = master
self.user_choice = StringVar()
self.user_choice.set("")
self.frame = Frame(master, padx=200, pady=200)
self.frame.grid()
self.q = Label(self.frame, text="What is {} x {} ?".format(x, y))
self.q.grid(row=0)
self.ans = Entry(self.frame, width=50, textvariable=self.user_choice)
self.ans.grid(row=1)
self.answer = x * y
self.sub = Button(self.frame, text="submit", command=self.correct)
self.sub.grid(row=3)
You can do that by inheriting the properties of Question1 to Question2:
That can be:
class Question2(Question1):
#you can access that by:
self.correct()
Other way is you can define a global function outside both the classes and you can easily access it.
Example:
#somewhere globally:
def correct():
#some code
class Question1():
correct()
class Question2():
correct()
I think you can develop more such ideas of using a function which will be required by multiple classes.
As #JenilDave answered, you need to define function outside class, inherit from other class.explicitly call class.
i.e. for last case:
class Question1:
def correct():
<codes>
class Question2:
q1 = Question1()
q1.correct()
or
Question1.correct(<Question1 instance>)
But since your 'correct' function are heavily dependent to Question1, you can't use either way, and reconstruct your codes.
Working example below:
Instead of generating question Class per questions, send lists of questions to one class.
Every time you succeed third time, you'll move on to next questions by poping list you've provided before.
When Lists are empty, pop() causes IndexError and program closes.
...
Since I can't get what variable 'p' stands for, I'm guessing it's number of successes(passes).
Full Code:
import random
from tkinter import Frame, Label, Entry, Button, StringVar, Tk
class QuestionFrame(Frame):
def __init__(self, master, question_answer):
super().__init__(master)
self.x, self.y = 0, 0
self.master = master
self.entries = question_answer
self.question, self.answer = self.entries.pop(0)
self.success = 0
self.user_choice = StringVar()
self.frame = Frame(master)
self.frame.grid()
self.quest_label = Label(self.frame)
self.ans = Entry(self.frame, width=50, textvariable=self.user_choice)
self.sub = Button(self.frame)
self.quest_label.grid(row=0)
self.ans.grid(row=1)
self.sub.grid(row=3)
self.reload_question()
def reload_question(self):
self.x, self.y = random.sample(range(5, 12), 2)
next_quest = f"What is {self.question.format(self.x, self.y)} ?"
self.quest_label.configure(text=next_quest)
self.ans.delete(0, 'end')
self.sub.configure(text="submit", command=self.correct)
def next(self):
print(self.success)
if self.success == 3:
# loads next entry
try:
self.question, self.answer = self.entries.pop(0)
except IndexError:
self.master.destroy()
else:
self.success = 0
self.reload_question()
else:
self.reload_question()
def correct(self):
self.sub.configure(text="Next", command=self.next)
if int(self.user_choice.get()) == self.answer(self.x, self.y):
self.quest_label['text'] = "Correct!"
self.success += 1
else:
self.quest_label['text'] = "Incorrect!"
if __name__ == '__main__':
# Passing questions with list of (question, answer) tuples.
tests = [("{} x {}", lambda x, y: x*y),
("{} - {}", lambda x, y: x-y)]
root = Tk()
root.title(f'Some fancy title')
window = QuestionFrame(root, tests)
window.mainloop()

Can't get to things in tkinter made in class

I'm new in Python and I'm currently trying to use tkinter as first GUI. I was used to making it without classes. And it is my first time to use import tkinter as tk instead of import *
import tkinter as tk
def update():
pass
#Game.statsFrame #doesn't work Game.statsFrame.stat1_amountLabel too
#Game.stat1_amountLabel #doesnt work < want to use update_idletasks() or
#just type new cofnig...
#just errors like: "Game' has no attribute 'statsFrame" etc #Game
class character:
name = ""
experience = 0
level = 0
gold = 0
stat1 = 0
stat2 = 0
stat3 = 0
stat4 = 0
stat5 = 0
avaiblePoints = 0
def add_stat1(self):
if self.avaiblePoints >= 1:
self.stat1 += 1
self.avaiblePoints -= 1
update()
else:
pass
def add_stat2(self):
if self.avaiblePoints >= 1:
self.stat2 += 1
self.avaiblePoints -= 1
update()
[...]
myChar = character()
myChar.avaiblePoints = 3
class Game:
def __init__(self, parent):
self.myParent = parent
self.myGame = tk.Frame(parent)
self.myGame.grid()
self.statsFrame = tk.Frame(self.myGame).grid()
self.stat1Label = tk.Label(self.statsFrame)
self.stat1Label.config(text="Strength:")
self.stat1Label.grid(column=1, row=1)
self.stat1_amountLabel = tk.Label(self.statsFrame)
self.stat1_amountLabel.config(text=myChar.stat1)
self.stat1_amountLabel.grid(column=2, row=1)
self.add_stat1Button = tk.Button(self.statsFrame)
self.add_stat1Button.config(text="+", command=myChar.add_stat1)
self.add_stat1Button.grid(column=3, row=1)
root = tk.Tk()
myapp = Game(root)
root.mainloop()
But I can't get to (for example) stat1Label and change text inside it and after it use update_idletasks(). It's like it doesnt exist. Errors shows that Game has not atributtes like stat1Label etc.
I want to use it becouse I have read that __init__ method is better and I want to swtich between pages. I have no idea, when I wasn't using class in tkinter some things (like this) was easier and had no problems. I'm very confused guys.
It's excellent that you're using import tkinter as tk instead of the dreaded "star" import, and that you're trying to organize your code with classes. It can be a little confusing at first, but it makes your code more modular, which helps enormously, especially when the GUI gets large.
There are a few problems with your code. The most important one is this line:
self.statsFrame = tk.Frame(self.myGame).grid()
The .grid method (and .pack and .place) all return None. So that line saves None to self.statsFrame, not the Frame widget. So when you later try to do stuff with self.statsFrame it won't do what you expect.
Another problem is that the text attribute of your self.stat1_amountLabel doesn't track the value of myChar.stat1, so when you change the value of myChar.stat1 you need to explicitly update the Label with the new value. Alternatively, you could use the textvariable attribute with an IntVar to hold the character's stat. See the entry for textvariable in the Label config docs for info.
Your character class has a whole bunch of attributes like name, experience etc as class attributes. That's not a good idea because class attributes are shared by all instances of a class. But you probably want each character instance to have their own instance attributes. So you should give character an __init__ method where you set those attributes. OTOH, it's ok to use class attributes for default values that get overridden by instance attributes.
Anyway, here's a repaired version of your code with a Button that updates the Strength stat. I've put the stats in a list, rather than having a bunch of separate named stats that would have to be managed separately. And I've given Game a make_stat method so you can easily add rows for the other stats.
import tkinter as tk
class Character:
def __init__(self, availablePoints=0):
self.name = ""
self.experience = 0
self.level = 0
self.gold = 0
self.stats = [0] * 5
self.availablePoints = availablePoints
def add_stat(self, idx):
if self.availablePoints >= 1:
self.stats[idx] += 1
self.availablePoints -= 1
class Game:
def __init__(self, parent):
self.myParent = parent
self.myGame = tk.Frame(parent)
self.myGame.grid()
self.statsFrame = tk.Frame(self.myGame)
self.statsFrame.grid()
self.make_stat("Strength:", 0, 0)
def make_stat(self, text, idx, row):
label = tk.Label(self.statsFrame, text=text)
label.grid(column=1, row=row)
amount = tk.Label(self.statsFrame, text=myChar.stats[idx])
amount.grid(column=2, row=row)
def update():
myChar.add_stat(idx)
amount["text"] = myChar.stats[idx]
button = tk.Button(self.statsFrame, text="+", command=update)
button.grid(column=3, row=row)
myChar = Character(3)
root = tk.Tk()
myapp = Game(root)
root.mainloop()
This code is still not ideal, but it's an improvement. ;) For example, it would be good to give Game a method for creating new characters, rather than creating them in the global context. You could store them in a dict attribute of Game, using the character's name as the key.
Here's a new version that works on separate named stat attributes. As I said in the comments, doing it this way is more complicated (and less efficient) than using a list to hold the stats.
import tkinter as tk
class Character:
def __init__(self, availablePoints):
self.name = ""
self.experience = 0
self.level = 0
self.gold = 0
self.stat1 = 0
self.stat2 = 0
self.stat3 = 0
self.stat4 = 0
self.stat5 = 0
self.availablePoints = availablePoints
class Game:
def __init__(self, parent):
self.myParent = parent
self.myGame = tk.Frame(parent)
self.myGame.grid()
self.statsFrame = tk.Frame(self.myGame)
self.statsFrame.grid()
self.make_stat("Strength:", "stat1", 1, 1)
def make_stat(self, text, stat, column, row):
label = tk.Label(self.statsFrame, text=text)
label.grid(column=column, row=row)
amount = tk.Label(self.statsFrame, text=getattr(myChar, stat))
amount.grid(column=(column+1), row=row)
def update():
if myChar.availablePoints >= 1:
v = getattr(myChar, stat) + 1
setattr(myChar, stat, v)
myChar.availablePoints -= 1
amount["text"] = v
button = tk.Button(self.statsFrame, text="+", command=update)
button.grid(column=(column+2), row=row)
myChar = Character(5)
root = tk.Tk()
myapp = Game(root)
root.mainloop()

how to change value of label after button is clicked on Tkinter

I am creating a simple bank account GUI , when i click the menu " interest" the variable changed from 1 to 2 , which should change the value of the current balance by 10 percent, however the value stays the same, give your insight.
from tkinter import *
from random import randint
class BankAccount(object):
def __init__(self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def get_balance(self, initial_balance, rate):
return self.get_balance() * self._rate
class BankAccountWithInterest(BankAccount):
def __init__(self, initial_balance=0, rate=0.1):
BankAccount.__init__(self, initial_balance)
self._rate = rate
def interest(self):
return self.balance * self._rate
balance = (randint(100, 500))
my_account = BankAccount(balance)
my_interest = BankAccountWithInterest(balance)
interest = my_interest.balance + my_interest.interest()
typeOfAccount = "1"
class GUI:
def __init__(self, master):
frame = Frame(master)
frame.pack()
#Toolbar#
toolbar = Frame(root)
toolbar.pack(side=TOP, fill=X)
#Button#
button1 = Button(toolbar, text="Deposit", width = 13, command=self.depositBalance)
button2 = Button(toolbar, text="Withdraw",width = 13, command=self.depositWithdraw)
button1.pack(side=LEFT)
button2.pack(side=RIGHT)
#Menu#
subMenu = Menu(menu)
menu.add_cascade(label="Type of Account", menu=subMenu)
subMenu.add_command(label="Standard", command= self.standard)
subMenu.add_command(label="Interest", command= self.interest)
#Textbox#
self.text = Entry(root)
self.text.pack()
#Labels#
w = Label(root, text="Current Balance:")
w.pack()
w1 = tkinter.StringVar()
if typeOfAccount == "1":
w1 = Label(root, text=my_account.balance)
w1.pack()
elif typeOfAccount == "2":
w1.set(text=interest)
w1.pack()
def depositBalance(self):
a = int(self.text.get())
my_account.balance = a + my_account.balance
print(my_account.balance)
def depositWithdraw(self):
a = int(self.text.get())
my_account.balance = my_account.balance - a
print(my_account.balance)
def standard(self):
typeOfAccount = "1"
def interest(self):
typeOfAccount = "2"
root = Tk()
menu = Menu(root)
root.config(menu=menu)
root.title("Bank Account")
root.minsize(width=250, height=100)
root.maxsize(width=300, height=150)
GUI(root)
root.mainloop()
There are several problems with your code. The multiple class files do not appear to work as you think they should and some things are just wrong. I have reworked your program into what I think it is you are trying to do and I have moved everything into 1 big class as it made more sense in this situation. You were making things more complicated than it needed to be by creating variables outside of the classes and by making several classes. There is nothing really wrong with using several classes but the way you were going about it was making things way more difficult than it needed to be.
First thing I did was to create all the class variables/attributes that we are going to use.
To make things easier on us going forward I made every widget and variable a class attribute by placing self. as a prefix to all the variable/widget names. This will allow us to interact with and change each attribute in any of the class methods without an issue and if you add more options down the road the attributes will already be defined and ready to change.
Next I moved all your separate class methods into the main class to make things easier to work with.
I replaced your if/else statement on the account types into a methods. This will allow us to update label to show the balance or the interest any time the account type changes or an amount is added or removed from the balance.
I modified the depositBalance and depositWithdraw methodsto have a little error handling because your entry field is not restricted to only numbers and can cause errors if the user puts anything else in or leaves it blank.
I change the standard and interest methods to update the typeOfAccount attribute and to update the label by calling on the type_account method.
Last but not least some general clean up so the code did not have pointless spacing and to make sure we follow a DRY (don't repeat yourself) standard.
Below is the reworked code with all the changes I mentioned above. Let me know if this helps and if you are confused on anything.
from tkinter import *
from random import randint
class GUI:
def __init__(self, master):
self.master = master
self.typeOfAccount = "1"
self.balance = (randint(100, 500))
self.rate = 0.1
self.frame = Frame(master)
self.frame.pack()
self.toolbar = Frame(root)
self.toolbar.pack(side=TOP, fill=X)
self.button1 = Button(self.toolbar, text="Deposit", width = 13, command=self.depositBalance)
self.button2 = Button(self.toolbar, text="Withdraw",width = 13, command=self.depositWithdraw)
self.button1.pack(side=LEFT)
self.button2.pack(side=RIGHT)
self.menu = Menu(self.master)
self.master.config(menu = self.menu)
self.subMenu = Menu(self.menu)
self.menu.add_cascade(label="Type of Account", menu=self.subMenu)
self.subMenu.add_command(label="Standard", command=self.standard)
self.subMenu.add_command(label="Interest", command=self.interest)
self.text = Entry(self.master)
self.text.pack()
self.w = Label(root, text="Current Balance: {}".format(self.balance))
self.w.pack()
#removed "tkinter." not needed because of the type of import you used
self.w1 = StringVar()
def type_account(self):
if self.typeOfAccount == "1":
self.w.config(text="Current Balance: {}".format(self.balance))
elif self.typeOfAccount == "2":
interest = self.balance * self.rate
self.w.config(text="Current Balance: {}".format(interest))
def depositBalance(self):
try:
if int(self.text.get()) > 0:
a = int(self.text.get())
self.balance = a + self.balance
self.type_account()
except:
print("Blank or non numbers in entry field")
def depositWithdraw(self):
try:
if int(self.text.get()) > 0:
a = int(self.text.get())
self.balance = self.balance - a
self.type_account()
except:
print("Blank or non numbers in entry field")
def standard(self):
self.typeOfAccount = "1"
self.type_account()
def interest(self):
self.typeOfAccount = "2"
self.type_account()
if __name__ == "__main__":
root = Tk()
root.title("Bank Account")
root.minsize(width=250, height=100)
root.maxsize(width=300, height=150)
app = GUI(root)
root.mainloop()
You should set self.w1, (rather than just w1) for example, then you can update the text from any instance method in that class.

How to only allow certain parameters within an entry field on Tkinter

If i want an entry box in Tkinter that only accepts floating point numbers that are greater than or equal to 0.0 and less than or equal to 1.0 how would i do that?
The proper way it to use tkinter's validate capabilities. But it's really a PIA to use.
dsgdfg has a good answer, but I can make that a lot neater, robust, and more dynamic:
import Tkinter as tk
class LimitedFloatEntry(tk.Entry):
'''A new type of Entry widget that allows you to set limits on the entry'''
def __init__(self, master=None, **kwargs):
self.var = tk.StringVar(master, 0)
self.var.trace('w', self.validate)
self.get = self.var.get
self.from_ = kwargs.pop('from_', 0)
self.to = kwargs.pop('to', 1)
self.old_value = 0
tk.Entry.__init__(self, master, textvariable=self.var, **kwargs)
def validate(self, *args):
try:
value = self.get()
# special case allows for an empty entry box
if value not in ('', '-') and not self.from_ <= float(value) <= self.to:
raise ValueError
self.old_value = value
except ValueError:
self.set(self.old_value)
def set(self, value):
self.delete(0, tk.END)
self.insert(0, str(value))
You use it just like an Entry widget, except now you have 'from_' and 'to' arguments to set the allowable range:
root = tk.Tk()
e1 = LimitedFloatEntry(root, from_=-2, to=5)
e1.pack()
root.mainloop()
If you want to call a button to check whether, this is a way to do it.
from tkinter import *
class GUI():
def __init__(self, root):
self.Entry_i = Entry(root, bd = 5)
self.test = StringVar()
Label_i = Label(root, textvariable = self.test)
Button_i = Button(root, text = "Go", command = self.floatornot)
self.Entry_i.grid()
Label_i.grid()
Button_i.grid()
mainloop()
def floatornot(self):
test = self.Entry_i.get()
if float(test) < 0 or float(test) > 1:
self.test.set("Good")
else:
self.test.set("")
root = Tk()
GUI(root)
The button will call the floatornot function. This will get the value of the entry and check if it okay or not. Depending on the result the value of the label will be changed.

Using tkinter library in Python

I have two python files gui.py, student.py. i have imported tkinter, i will ask the user to enter their name, id, email, and address, Using tkinter widget i will display all in a list. How to do this using class ?
this is gui.py
import tkinter
import student
class MyGUI:
def __init__(self):
self.__students = []
# Create the main window widget
self.main_window = tkinter.Tk()
self.name_f = tkinter.Frame(self.main_window)
self.id_f = tkinter.Frame(self.main_window)
self.email_f = tkinter.Frame(self.main_window)
self.addy_f = tkinter.Frame(self.main_window)
self.buttons_f = tkinter.Frame(self.main_window)
# Create a Label and Entry widget for each item in
# the Student class
self.name_l = tkinter.Label(self.name_f, text='Name: ')
self.name_e = tkinter.Entry(self.name_f, width=10)
self.id_l = tkinter.Label(self.id_f, text='ID: ')
self.id_e = tkinter.Entry(self.id_f, width=10)
self.email_l = tkinter.Label(self.email_f, text='Email: ')
self.email_e = tkinter.Entry(self.email_f, width=10)
self.addy_l = tkinter.Label(self.addy_f, text='Address: ')
self.addy_e = tkinter.Entry(self.addy_f, width=10)
self.add_b = tkinter.Button(self.buttons_f, text='Add Current Data', command=self.add)
self.display_b = tkinter.Button(self.buttons_f, text='List All', command=self.display)
self.quit_b = tkinter.Button(self.buttons_f, text='Quit', command=self.main_window.destroy)
self.name_l.pack(side='left')
self.name_e.pack(side='left')
self.id_l.pack(side='left')
self.id_e.pack(side='left')
self.email_l.pack(side='left')
self.email_e.pack(side='left')
self.addy_l.pack(side='left')
self.addy_e.pack(side='left')
self.add_b.pack(side='left')
self.display_b.pack(side='left')
self.quit_b.pack(side='left')
self.name_f.pack()
self.id_f.pack()
self.email_f.pack()
self.addy_f.pack()
self.buttons_f.pack()
#Enter the tkinter main loop
tkinter.mainloop()
def add(self):
# we will do this in class
pass
def display(self):
# we will do this in class
pass
# Create an instance of the MyGUI class
my_gui = MyGUI()
and this is the student.py
class Student:
# this a comment
# most languages define attributes sep
# Declare String name
def setName(self, n):
self.name = n
def setId(self, i):
self.sid = i
def setEmail(self, e):
# check to see if e has an # sign
self.email = e
def setAddy(self, a):
self.addy = a
def getName(self):
return self.name
def getId(self):
return self.sid
def getEmail(self):
return self.email
def getAddy(self):
return self.addy
def printInfo(self):
info = "Name: "
info += self.name
info += '\nID: '
info += self.sid
info += '\nEmail: '
info += self.email
info += '\nAddress: '
info += self.addy
info += '\n'
return info
Asking for code solutions to something you should be learning yourself probably isn't a good idea.
Just look up the documentation for TKinter here: https://docs.python.org/3/library/tkinter.html
As a note, you may want to consider opening separate windows when displaying the information. When I first learned TKinter, I first practiced by printing all my data to the console with the print command before trying to force them into tables.
Also, consider fleshing out the GUI and make it look like a table. Give each label a fixed length and each box a fixed length, this will make it look better.
A good example of this in action is on this amazing website for learning TKinter: http://www.tkdocs.com/tutorial/firstexample.html
Just scroll down until you find the Python implementation of the code :)

Categories

Resources