Executing a function prevents tkinter window from appearing - python

I have a function that is going to be the main area of this program, but when I add in a new function that needs to be executed by a button, it prevents the window from appearing, or gives out an error. The function I am trying to get to appear after a button press is new_function.
def bowler():
global bowler_win
global batsmen
bowler_win = Toplevel(master)
batsmen_win_2.withdraw()
variable = StringVar(bowler_win)
variable.set(fielding_team[0])
title = Label(bowler_win, text = "Please choose the bowler").grid(row = 0, column = 1)
w = OptionMenu(bowler_win, variable, *fielding_team)
w.grid(row = 1, column = 1)
def ok2():
current_bowler = variable.get()
for players in batting_team:
if players == current_bowler:
fielding_team.remove(current_bowler)
main_play()
button = Button(bowler_win, text="OK", command=ok2).grid(row = 2, column = 1)
#####CODE ABOVE IS ONLY TO SHOW WHERE THE FUNCTION BELOW IS EXECUTED FROM
def main_play():
while innings != 3:
facing_length = len(batsmen)
while over != over_amount or out_full == True or facing_length <= 1:
main_win = Toplevel(master)
bowler_win.withdraw()
ws = Label(main_win, text = " ").grid(row = 1, column = 1)
title = Label(main_win, text = "Current Game").grid(row = 0, column = 1)
score = Label(main_win, text = "Current Score:").grid(row = 2, column = 1)
line = Label(main_win, text = "--------------").grid(row = 1, column = 1)
score = Label(main_win, text = str(runs) + "/" + str(out)).grid(row = 3, column = 1)
line = Label(main_win, text="--------------").grid(row=4, column=1)
cur_bat = Label(main_win, text = "Facing Batsmen: " + batsmen[0]).grid(row = 5, column = 1)
other_bat = Label(main_win, text = "Other Batsmen: " + batsmen[1]).grid(row = 6, column = 1)
current_patner = Label(main_win, text = "Patnership: " + str(partnership_runs)).grid(row = 7, column = 1)
button = Button(main_win, text = "Next Play", command = new_function).grid(row = 8, column = 1) ###THIS IS WHERE THE NEW FUNCTION IS EXECUTED
If I call the function new_function after the button, the main_win window does not appear, this is the same for if I call new_function above the main_play function, the same error occurs.
If I try to nest new_function below the button, I get the error
UnboundLocalError: local variable 'new_func' referenced before assignment
Even though its a function(and I don't have a variable named that)
If anyone can help, that would be amazing

Related

object in not callable in GUI temperature converter

I'm doing an assignment in Python for a converter between Celsius and Fahrenheit.
The GUI frame appears but the terminal says the FloatField object isn't callable. the error resides within the computeCelsius function within the line that says getNumber(). Trying to ind a solution please help.
from breezypythongui import EasyFrame
class TemperatureConverter(EasyFrame):
"""A termperature conversion program."""
def __init__(self):
"""Sets up the window and widgets."""
EasyFrame.__init__(self, width = 1000, title = "Temperature Converter")
self.addLabel(text = "Celsius", row = 0, column = 0)
self.addLabel(text = "Fahrenheit", row = 0, column = 1)
self.CelsiusField = self.addFloatField(value = 0.0, row = 1, column = 0)
self.FahrenheitField = self.addFloatField(value = 32.0, row = 1, column = 1)
self.grp1 = self.addButton(text = ">>>>", row = 2, column = 0, command = self.computeFahrenheit)
self.grp2 = self.addButton(text = "<<<<", row = 2, column = 1, command = self.computeCelsius)
def computeFahrenheit(self):
inputVal = self.CelsiusField().getNumber()
farh = 9.0/5.0 * inputVal + 32
self.getInputFahrenheit.setValue(farh)
def computeCelsius(self):
inputVal = self.FahrenheitField().getNumber()
cels = (farh - 32) * 5.0/9.0
self.getInputCelsius.setValue(cels)
def main():
"""Instantiate and pop up the window."""
TemperatureConverter().mainloop()
if __name__ == "__main__":
main()

How do I delete a specific label on a frame that doesn't seem to have a name?

currently I'm trying to create a button that deletes the labels another function produces. This other function creates labels all with the same name, like so:
def display():
global overall_data
length = len(overall_data)
print(length)
for i in range(len(overall_data)):
print("i = " + str(i))
bg_colour = "Black"
l = tk.Message(my_frame3,
text = "Name = " + str(overall_data[i][0]) + "\n"
"Health = /" + str(overall_data[i][1]) + " \n"
"Armour Class = " + str(overall_data[i][2]) + "\n"
"Initiative = " + str(overall_data[i][3]),
fg='White',
bg=bg_colour)
l.place(x = 20 + i*150, y = 60, width=120, height= 80)
string = str(overall_data[i][1])
data = tk.StringVar(my_frame3, value = string)
health_input = tk.Entry(my_frame3, textvariable = data, width = 15,fg = "Black",bg = "White")
health_input.place(x = 85 + i*150, y = 85, width = 25, height=15)
Basically, overall_data is a 2d array. This function will output each part of the array one at a time, e.g [[1,2,3,4], [2,3,4,5]],it would output one label for [1,2,3,4] and another for [2,3,4,5].
Now I have another function that should remove all the labels produced by this function. Currently I tried just using:
def remove_labels():
my_frame3.destroy()
but this deletes the entire frame, which is self explanatory but I thought I might as well give it a shot. Another thing I tried is l.destroy(), but it also didn't work saying that l has not been defined which I think is because its a temporary variable existing just inside the for loop. I made l global, but then only the latest label for l would be destroyed. I've seen some answers suggesting pack, but I've been avoiding it in my code since I found place easier. Although if they are no other options I'll use it.
If my_frame3 contains only the widgets you want to destroy later, then you can modify remove_labels() as below:
def remove_labels():
for child in my_frame3.winfo_children():
child.destroy()
Got help in the comments, but posting here so it's easier to see. Basically just save the labels in a list as they are created and destroy them one by one later. Like this:
def display():
global x
x = []
global y
y = []
global overall_data
length = len(overall_data)
print(length)
for i in range(len(overall_data)):
print("i = " + str(i))
global l
bg_colour = "Black"
l = tk.Message(my_frame3,
text = "Name = " + str(overall_data[i][0]) + "\n"
"Health = /" + str(overall_data[i][1]) + " \n"
"Armour Class = " + str(overall_data[i][2]) + "\n"
"Initiative = " + str(overall_data[i][3]),
fg='White',
bg=bg_colour)
x.append(l)
l.place(x = 20 + i*150, y = 60, width=120, height= 80)
string = str(overall_data[i][1])
data = tk.StringVar(my_frame3, value = string)
health_input = tk.Entry(my_frame3, textvariable = data, width = 15,fg = "Black",bg = "White")
health_input.place(x = 85 + i*150, y = 85, width = 25, height=15)
y.append(health_input)
def remove_labels():
for i in range(len(x)):
x[i].destroy()
for i in range(len(y)):
y[i].destroy()

creating an object doesn't work

class phonebook:
def __init__(self,first_name, last_name, street, postcode, city, number):
root = tk.Tk()
root.title('Book')
menubar = tk.Menu(root)
root.config(menu = menubar)
menubar.add_command(label = 'Anlegen', command = self.create)
menubar.add_command(label = 'Bearbeiten', command = self.change)
menubar.add_command(label = 'Löschen')
menubar.add_command(label = 'Sortieren')
menubar.add_command(label = 'Suche')
menubar.add_command(label = 'Hilfe')
root.mainloop()
def printing(self):
account = (self.first_name.get(), self.last_name.get(), self.street.get(), self.postcode.get(), self.city.get(), self.number.get())
accounts.append(account)
for i in accounts:
print(i)
def change(self):
account = accounts[0]
account.first_name = 'test'
self.printing
def create(self):
creation = tk.Toplevel()
tk.Label(creation, text = 'Vorname').grid(row = 1, column = 0)
tk.Label(creation, text = 'Nachname').grid(row = 2, column = 0)
tk.Label(creation, text = 'Stadt').grid(row = 3, column = 0)
tk.Label(creation, text = 'Postleitzahl').grid(row = 4, column = 0)
tk.Label(creation, text = 'Straße').grid(row = 5, column = 0)
tk.Label(creation, text = 'Telefonnummer').grid(row = 6, column = 0)
self.first_name = tk.Entry(creation)
self.last_name = tk.Entry(creation)
self.city = tk.Entry(creation)
self.postcode = tk.Entry(creation)
self.street = tk.Entry(creation)
self.number = tk.Entry(creation)
a = tk.Button(creation, text = 'end', command = self.printing)
self.first_name.grid(row = 1, column = 1)
self.last_name.grid(row = 2, column = 1)
self.city.grid(row = 3, column = 1)
self.postcode.grid(row = 4, column = 1)
self.street.grid(row = 5, column = 1)
self.number.grid(row = 6, column = 1)
a.grid(row = 7, column = 1)
phonebook()
As you can see in my code I'm trying to create and edit objects. The problem is that I cannot create a real object. When I want to create a object with class phonebook, I get this error:
TypeError: __init__() missing 6 required positional arguments: 'first_name', 'last_name', 'street', 'postcode', 'city', and 'number'
What do I have to do so that I don't get this error and so that I can edit the objects?
phonebook must be called with 6 arguments, not 0. You call phonebook(), which causes your code to break. Try calling with something like this:
phonebook("first_name", "last_name", "street", "post_code", "your_city", 123)
substitute in the appropriate values instead of the ones I've provided.
P.S. You won't get much help on this site with a username like that

Python timetable pass start and finish time that pressed button relevant to position

For my coursework i am making a booking system and i have been messing around trying to make a page which shows current week lessons and when the button is clicked it comes up with that students details on a separate page.But i don't know how to go about passing that time into my open page sub(which writes a txt file which is going to be used for SQL to get the students details). The current way i have done it just passes the max times into the sub.
from tkinter import *
import datetime
class Application(Frame):
def __init__(self, master):
""" Initialize the frame. """
super(Application, self).__init__(master)
self.grid()
self.timetable_button_gen_weekdays()
self.timetable_button_gen_weekends()
def timetable_button_gen_weekdays(self):
c = datetime.datetime(100,1,1,16,00,00)
self.Monday_lbl = Label(self, text = "Monday")
self.Monday_lbl.grid(row = 1, column = 0)
self.Tuesday_lbl = Label(self, text = "Tuesday")
self.Tuesday_lbl.grid(row = 2, column = 0)
self.Wednesday_lbl = Label(self, text = "Wednesday")
self.Wednesday_lbl.grid(row = 3, column = 0)
self.Thursday_lbl = Label(self, text = "Thursday")
self.Thursday_lbl.grid(row = 4, column = 0)
self.Friday_lbl = Label(self, text = "Friday")
self.Friday_lbl.grid(row = 5, column = 0)
for k in range(8):
b = c + datetime.timedelta(minutes = (30 * k))
d = b + datetime.timedelta(minutes = (30))
self.i_time_weekdays_lbl = Label(self, text = b.time().strftime('%H:%M')+" to "+d.time().strftime('%H:%M'))
self.i_time_weekdays_lbl.grid(row = 0, column = k + 1)
for i in range(5):
for a in range(8):
b = c + datetime.timedelta(minutes = (30 * a))
d = b + datetime.timedelta(minutes = (30))
bttn_i_a = Button(self, text = "available",command = lambda: self.OpenPage(b.time().strftime('%H:%M'),d.time().strftime('%H:%M')))
bttn_i_a.grid(row = i + 1, column = a + 1)
bttn_i_a.config(height = 2, width = 10)
def timetable_button_gen_weekends(self):
c = datetime.datetime(100,1,1,10,00,00)
self.Saturday_lbl = Label(self, text = "Saturday")
self.Saturday_lbl.grid(row = 8, column = 0)
self.Sunday_lbl = Label(self, text = "Sunday")
self.Sunday_lbl.grid(row = 9, column = 0)
self.weekend_lbl = Label(self, text = "Weekend")
self.weekend_lbl.grid(row = 6, column = 1, sticky = W)
for k in range(10):
b = c + datetime.timedelta(minutes = (30 * k))
d = b + datetime.timedelta(minutes = (30))
self.i_time_weekdays_lbl = Label(self, text = b.time().strftime('%H:%M')+" to "+d.time().strftime('%H:%M'))
self.i_time_weekdays_lbl.grid(row = 7, column = k + 1)
for i in range(2):
for a in range(10):
b = c + datetime.timedelta(minutes = (30 * a))
d = b + datetime.timedelta(minutes = (30))
bttn_i_a = Button(self, text = "available",command = lambda: self.OpenPage(b.time().strftime('%H:%M'),d.time().strftime('%H:%M')))
bttn_i_a.grid(row = i + 8, column = a + 1)
bttn_i_a.config(height = 2, width = 10)
def OpenPage(self,startime,finishtime):
file = open("PassTimes.txt","w")
file.write(startime)
file.write("\n")
file.write(finishtime)
print(startime)
print(finishtime)
filepath = "PresentStudent.py"
global_namespace = {"__file__": filepath, "__name__": "__main__"}
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), global_namespace)
root = Tk()
root.title("test")
root.geometry("2000x2000")
app = Application(root)
root.mainloop()
Welcome to SO.
General
IMHO, running the main routine of "PresentStudent.py" does not look that clean.
It works, but a main routine is built for when the script is called directly, not when it is imported and used in some other script.
Are you aware of the modules functionality in python?
I would recommend creating a function in PresentStudent.py that does what you are doing inside your main routine. Give the function parameters to pass the .txt-Filename.
e.g.
def presentStudentCall(inputFile):
and use it inside your script like:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# here we import PresentStudent.py, as we import it __main__ will not run
import PresentStudent
#[...]
def OpenPage(self, stime, etime):
#[...]
# Instead of executing a file we call the function from the module
PresentStudent.presentStudentCall(file)
If you want to display the data inside a second frame, you could also declare a class in PresentStudent.py and use it like:
def OpenPage(self, stime, etime):
#[...]
student=PresentStudent.Student() # assuming to name the class "Student"
student.presentStudentCall(file)
Your question itself
using the lambda does not need to be the best way. In matters of scope and garbage collecting your code only passes the last generated "b"s and "c"s to the definition.
What you could do to make it work is calculating the sender item in OpenPage:
To achieve that, I recommend having arrays for your time spans storing starting times.
Like
c = datetime.datetime(100,1,1,16,00,00)
self.weektimes = ["%s"%(c+datetime.timedelta(minutes=30*k)) for k in range(8)]
self.weekendtimes = ["%s"%((c+datetime.timedelta(minutes=30*k)) for k in range(10)]
First you need to bind the click event to the widget(in that case your button)
bttn_i_a.bind("<Button-1>", self.OnPage)
Your OpenPage could then look like this:
def OpenPage(self, event):
import time
# With that, we get the row and column where we clicked in
grid_info=event.widget.grid_info()
# week or weekend?
if grid_info["row"] > 5: #may depend on amount of headers
_timearray=self.weekendtimes
else:
_timearray=self.weektimes
# get the column
col=grid_info["column"]
# get the startTime
stime=_timearray[col]
# end time is +30 minutes
etime="%s"%(time.strptime("%s"%stime, "%H:%M")+time.struct_time(tm_min=30))
# now call the handler...

python tkinter accepting user input through function

1) I receive an Attribute Error for myText_Box
2) My goal is to accept user input through a text box and then define the word through an API definition method.
3) I am about to utilize this post to ask for a string -- How cold I resolve the attribute error? Following this post I was attemtping something along the lines of calc.myText_Box
calc = tk.Tk()
calc.title("VocabU")
Question_1 = str("Define which word?")
FRONT_PAGE = ['Define me!', Question_1]
def retrieve_input():
input = calc.myText_Box.get("1.0",'end-1c')
define_me = dictionary.get_definition(input)
return define_me
USER_INP = retrieve_input()
#RESPONSE = str(dictionary.get_definition(input))
# set up GUI
row = 1
col = 0
for i in FRONT_PAGE:
button_style = 'raised'
#action =
action = lambda x = retrieve_input(): click_event(x)
tk.Button(calc, text = i, width = 17, height = 3, relief = button_style, command = action).grid(row = row, column = col, sticky = 'nesw')
col += 1
if col > 0: # if col > 4
col = 0
row += 1
display = tk.Entry(calc, width = 40, bg = "white", text = Question_1)
#display.pack
display.grid(row = 2, column = 0, columnspan = 1) # columnspan = 5
You have not defined myText_Box anywhere in the code at https://github.com/phillipsk/dictionary_Merriam-Webster_API.
Attempting to reference it will raise an Attribute error, as will an attempt to access any undefined attribute on an object:
>>> a = object()
>>> a.myText_Box
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'myText_Box'
You need to create your Text widget and assign it to your Tk() instance, calc:
calc.myText_Box = Text(...)
input is a reserved word in Python, try to use a different one!

Categories

Resources