python tkinter accepting user input through function - python

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!

Related

in tkinter.entry using in for loop but when value changed that effect all entery

Here is the code of my application
problem
I have used tkinter Entry() method in for loop in ShowOpeanFile() function and I have make One global list variable where I stored the return value of Entry() but when I enter value in that Entry field it effect on all Entry. But I don't want that.
#importing Required library
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
import pandas as pd
from functools import reduce
#Global Variables to Store FilePath That OPEAN
Opean_file_path = []
#Making gloabl datagram object store variable
datgramoffileVariable = []
datagram_list = []
finaldatagram_list = []
#get Filename and qauntity
def getvalue(i):
if Opean_file_path[i][2].get().isnumeric():
return Opean_file_path[i][1],Opean_file_path[i][2].get(),Opean_file_path[i][0]
else:
return -1
#variable making function for file that map each open file during converxlsx function
def variablemaking(size):
temp = []
for number in range(size):
temp.append(str(number))
temp = (list(set(temp)))
datgramoffileVariable.clear()
for i in range(len(temp)):
datgramoffileVariable.append(temp[i])
#conevrting all file to dataGram using pandas library
def Converxlsx():
#makingVariable functioncall
variablemaking(len(Opean_file_path))
#Now variable Making function Done
#Go for the convert datagram to file
for i in range(len(datgramoffileVariable)):
datgramoffileVariable[i] = pd.DataFrame(pd.read_excel(Opean_file_path[i][0]))
for i in range(len(datgramoffileVariable)):
print(datgramoffileVariable[i])
#subpart of Compute function find in list return filepath
def find(target):
for i in range(len(Opean_file_path)):
if(Opean_file_path[i][1] == target):
return Opean_file_path[i][0]
return -1
def findindex(tar):
for i in range(len(Opean_file_path)):
print(Opean_file_path[i][0])
if(Opean_file_path[i][0] == tar):
return i
#ComputeFile function
def compute():
for i in range(len(Opean_file_path)):
v = getvalue(i)
if v == -1:
pass
else:
answerOffind = v[0]
if( answerOffind == -1):
if(label_for_error.cget('text') == "enter right file name"):
label_for_error.config(text="")
else:
label_for_error.config(text="enter right file name", fg='red')
else:
label_for_error.config(text="")
if(len(v[1]) == 0 or v[1].isalpha() or v[1] == ' '):
label_for_error.config(text="enter right Qauntity", fg='red')
pass
else:
if v[1].isnumeric():
if(label_for_error.cget('text') == "enter right Qauntity"):
label_for_error.config(text='')
indexofmaniuplation = findindex(v[2])
print(indexofmaniuplation)
datgramoffileVariable[indexofmaniuplation].qauntity = datgramoffileVariable[indexofmaniuplation].qauntity * int(v[1])
# opeanfile function
def ShowOpeanFile():
col = 0
ro = 0
for i in range(len(Opean_file_path)):
ro = ro + 1
for j in range(len(Opean_file_path[i])):
if j > 1:
Opean_file_path[i][j] = tk.Entry(window,width=20,textvariable=1)
Opean_file_path[i][j].grid(row=ro,column=col)
else:
e = tk.Entry(window, width=20, fg='blue')
e.grid(row=ro,column=col)
e.insert(tk.END,Opean_file_path[i][j])
col = col + 1
col = col - 2
for i in range(len(Opean_file_path)):
for j in range(len(Opean_file_path[i])):
print(Opean_file_path[i][j])
#browsefile function
def browseFiles():
#opeanFile only allow Excel file
'''
askopenfile return file path of selected file
it return type is String
'''
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a File",
filetypes = [("Excel file","*.xlsx"),("Excel file", "*.xls")]
)
#After getting filepath storing into Opean_file_path list
if(filename in Opean_file_path):
pass
else:
tmp = []
tmp.append(filename)
f=filename.split('/')
tmp.append(f[-1])
tmp.append('qauntitybox')
Opean_file_path.append(tmp)
print(tmp)
Converxlsx()
ShowOpeanFile()
# print(Opean_file_path)
#making final CSV File function.
def csv_making():
datagram_list.clear()
finaldatagram_list.clear()
#convert dataframe into list
for i in range(len(datgramoffileVariable)):
datagram_list.extend(datgramoffileVariable[i].values.tolist())
#find repted element and compute all at one single
repted_element = []
datagram_index_to_be_removed=[]
for i in range(len(datagram_list)):
temp_id = datagram_list[i][0]
temp_Qauntity = datagram_list[i][1]
for j in range(i+1,len(datagram_list)):
if datagram_list[j][0] == temp_id:
temp_Qauntity = temp_Qauntity + datagram_list[j][1]
datagram_index_to_be_removed.append(j)
datagram_index_to_be_removed.append(i)
if [temp_id,temp_Qauntity] not in repted_element and datagram_list[j][0] == temp_id:
repted_element.append([temp_id,temp_Qauntity])
datagram_index_to_be_removed = list(tuple(datagram_index_to_be_removed))
#remove repeted element
datagram_index_to_be_removed.sort()
for i in range(len(datagram_list)):
if i in datagram_index_to_be_removed:
pass
else:
finaldatagram_list.append(datagram_list[i])
#add repted_element
for i in repted_element:
finaldatagram_list.append(i)
#print final data
# print(finaldatagram_list)
#convert final list to csv
id = []
qauntityto = []
for i in range(len(finaldatagram_list)):
id.append(finaldatagram_list[i][0])
qauntityto.append(finaldatagram_list[i][1])
dict = {'id':id,'qauntity':qauntityto}
df = pd.DataFrame(data=dict)
pathofnewfile = df.to_csv('/home/vegg/Desktop/out.csv',index=False)
print(pathofnewfile)
label_for_error.config(text='file save at /home/vegg/Desktop/out.csv',fg='blue')
#UI
window = tk.Tk()
scrollbar = tk.Scrollbar()
frame = tk.Frame(window)
window.geometry("750x400")
label_for_qautity = tk.Label(window ,text="Enter the Qauntity",
width=50,height=3)
label_for_qautity.grid(column=2,row=0)
# Qauntity = tk.Entry()
# Qauntity.grid(column=2,row=1)
label_for_fileNamepath = tk.Label(window ,text="File Name path",
width=20,height=3)
label_for_fileNamepath.grid(column=0,row=0)
label_for_fileName = tk.Label(window ,text="File Name",
width=20,height=3)
label_for_fileName.grid(column=1,row=0)
label_for_error = tk.Label(window ,text="",
width=20,height=3)
label_for_error.grid(column=4,row=3)
button_explore = tk.Button(window,
text = "Browse Files here",
command=lambda :[browseFiles()] )
button_Compute = tk.Button(window,
text = "Compute File Data",
command=lambda :[compute()] )
button_CSV = tk.Button(window,
text = "Create CSV Here",
command=lambda :[csv_making()] )
button_explore.grid(column=4,row=0)
button_Compute.grid(column=4,row=1)
button_CSV.grid(column=4, row=2)
window.mainloop()
Image
I want to add different value for entry not same value effect to all entry.

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

Executing a function prevents tkinter window from appearing

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

Automatic calculation - Remove initial values

I have created a GUI where you can enter values (x values) manually. If you enter a value x1, trace-method will automatically calculate
f(x1)=x1^2=y1 and mean(y) = (1/5 sum_{i=1}^{5} y_i)
So every time an x-value is entered, the corresponding y-value and mean(y) is calculated. The code below works. If you start it you get:
I would like to remove the initial values 0.0 from some cells. The window should look like this when the code is executed:
To get the desired result, I added at the very end before mainloop()
for i in range(1,5):
y_values[i].set("")
cells[(i,0)].delete(0,END)
where i remove the initial values of certain cells. If you start the code with this change, the program will not work properly anymore. If you enter an x-value, only the corresponding y-value is calculated, but not mean(y).
Do any of you know why the code with y_values[i].set(""), cells[(i,0)].delete(0,END) no longer works correctly and how to solve this problem?
Here is the full Code (from picture 1):
from tkinter import *
import tkinter as tk
root = Tk()
Label(root, text = "x-values",padx = 10).grid(row = 0, column = 0)
Label(root, text = "y-values",padx = 10).grid(row = 0, column = 1)
Label(root, text = "Mean y", padx = 10).grid(row = 0, column = 2)
# Create Variables
x_values, y_values = ["x%d" % x for x in range(5)], ["y%d" % x for x in range(5)]
for i in range (5):
x_values[i], y_values[i] = DoubleVar(), DoubleVar()
mean = DoubleVar()
# Create Table
rows, columns, cells = 5, 2, {}
for i in range(columns):
for j in range(rows):
if i == 0: # x-values that can be entered
b = Entry(root, textvariable=x_values[j])
b.grid(row = j+1, column = i, sticky = W + E)
cells[(j,i)] = b
else: # y-values that are computed by f
b = Label(root, textvariable=y_values[j])
b.grid(row = j+1, column = i, sticky = W + E)
cells[(j,i)] = b
label_mean = Label(root, textvariable = mean).grid(row = 1, column = 2, rowspan = 5)
# compute y-values
def f(name, index, mode):
try:
for i in range(5):
y_values[i].set(x_values[i].get()**2)
except tk.TclError:
pass
# compute mean and standard deviation
def statistic(name, index, mode):
try:
y_sum = 0
for i in range(5):
y_sum += y_values[i].get()
y_normalized = y_sum / 5
mean.set(y_normalized)
except tk.TclError:
pass
# Traces to trigger the above functions
for i in range(5):
x_values[i].trace('w', f)
y_values[i].trace('w', statistic)
mainloop()
Mean is not calculating because it is raising exception when you tried to add None value to y_sum. Add try block in your statistics function.
def statistic(name, index, mode):
try:
y_sum = 0
for i in range(5):
try:
y_sum += y_values[i].get()
except:
pass
y_normalized = y_sum / 5
mean.set(y_normalized)
except tk.TclError:
pass

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...

Categories

Resources