Python tkinter get() has no attribute - python

I'd like to use each variable in the list in an Entry widget, and get the text after pressing a button.
self.input_text = ['l1', 'l2', 'l3']
self.activeRow = 3
for e in self.input_text:
e = StringVar()
t = Entry(textvariable=e)
t.grid(row=self.activeRow,column=4,columnspan=2,sticky=W)
self.activeRow += 1
Eventually, I'd like to write the value of each variable in the list to a file but for now, I can't seem to print self.input_text[0] after the button press.
button1 = Button(text='Write',command=self.__writeNewInfo, width = 15)
button1.grid(row=self.activeRow,column=5,sticky=W)
def __writeNewInfo(self):
x = self.input_text[0].get()
y = self.input_text[1].get()
z = self.input_text[2].get()
print x
print y
print z

You are doing the wrong thing when creating the instances of StringVar. You set e to be the item in the list, then overwrite it as an empty StringVar. Instead try:
for i, e in enumerate(self.input_text):
self.input_text[i] = StringVar() #Overwrite this item in the list
self.input_text[i].set(e) #Set the StringVar to take the value from the list
t = Entry(textvariable=self.input_text[i])
t.grid(row=self.activeRow,column=4,columnspan=2,sticky=W)
self.activeRow += 1

self.input_text is basically a list of strings. If you want to retrieve something from an entry you need to keep the variable of this entry and call get() on it.
for example:
self.input_text = ['l1', 'l2', 'l3']
self.entries = []
self.activeRow = 3
for e in self.input_text:
e = StringVar()
t = Entry(textvariable=e)
t.grid(row=self.activeRow,column=4,columnspan=2,sticky=W)
self.activeRow += 1
self.entries.append(t)
button1 = Button(text='Write',command=self.__writeNewInfo, width = 15)
button1.grid(row=self.activeRow,column=5,sticky=W)
def __writeNewInfo(self):
x = self.entries[0].get()
y = self.entries[1].get()
z = self.entries[2].get()
print x
print y
print z

Related

Add 2 numbers from separate buttons (tkinter)

I have 3 buttons I want to make it so when you press a button it sets the variable to a value.
press 1st button sets x to 1 2nd set y to 2 press 3rd add x and y together should return with 3 but it returns with 0.
I tried to make a 4th value where when it is set to 1 it would add both together. me and a friend tried making x and y at the beginning and integer int(x)= x
here is the code
import tkinter
window_main = tkinter.Tk(className='Tkinter - TutorialKart', )
window_main.geometry("400x200")
i=0
x=0
y=0
o = 0
p = 0
x = int(x)
y = int(y)
o = int(o)
p = int(p)
i=int(i)
def submitFunction() :
x = 1
print(x)
if o == 1:
x = 1
def a2():
y = 2
print(y)
if p == 1:
y = 2
def equ():
i = int(x + y)
return(i)
print(i)
button_submit = tkinter.Button(window_main, text ="set x to 1", command=submitFunction).grid(column = 1, row = 1)
button = tkinter.Button(window_main, text ="set y to 2", command=a2).grid(column = 2, row = 1)
button = tkinter.Button(window_main, text = "solve", command = equ). grid(column = 3, row = 1)
window_main.mainloop()
Given your code if you look carefully there are two Variables by the name 'x' and 'y' and whenever you press the button it does execute the button however the variables in inside those function are treated as local variables although you have defined them outside the function which should make them global variables.
But in the case of python global variables can be accessed inside the function but cannot be modified.
So in this case in order to treat the 'x' and 'y' with global scope so they can be modified or changed inside the function which reflects it variables outside, we use global Keyword inside function in order to make their scope global.
I have modified your code a bit.
from tkinter import *
import tkinter
window_main = Tk(className='Tkinter - TutorialKart', )
window_main.geometry("400x200")
i=0
x=0
y=0
o = 0
p = 0
def submitFunction() :
global x
x = 1
print(x)
if o == 1:
x = 1
def a2():
global y
y = 2
print(y)
if p == 1:
y = 2
def equ():
i = x + y
print(i)
return (i)
button_submit = tkinter.Button(window_main, text ="set x to 1", command=submitFunction).grid(column = 1, row = 1)
button = tkinter.Button(window_main, text ="set y to 2", command=a2).grid(column = 2, row = 1)
button = tkinter.Button(window_main, text = "solve", command = equ). grid(column = 3, row = 1)
window_main.mainloop()
If you want to read more about calling functions in tkinter without parenthesis click this link the person has explained it perfectly.
Also check variable scoping in Python link
You might get more clarity on understanding your problem after reading.

Search in list of tkinter widgets

I have some tkinter widgets stored in a list. I'd like to search for an object in that list, by I don't know the syntax.
import tkinter as tk
main = tk.Tk()
base = tk.Frame(main).pack()
l = []
for i in range(3):
et = tk.Label(base, text='label '+str(i))
et.pack()
l.append(et)
print(base.Label.!label in l)
main.mainloop()
Note.
Certainly this is a minimal example to understand where my mistake is.
The gui actually consists of an n x m matrix of tkinker entries, whose cells, rows, and columns should be dynamically added, deleted, modified, and even inserted or switched.
To do this, I have a dictionary that associates index tuples (i,j) with tkinter entries. When an entry is chosen with the mouse, that object is known, but what I really need to know is its index (i,j) to manage all the rest of the information (maths operations over arrays, etc).
To solve your problem you could use the index of separate list and use widget.grid_info() to retrieve the indices.
top_bar = []
sidebar = []
The rendering and the content have separated masters to achieve that the indexes of the lists, which starts with 0, match with the column and row of your inner grid.
The outer master could be populated like this, important to note is that Label on grid position 0,0 is not append to any of the lists but is gridded to fill the space. The grid_configure is just a optical improvement.
def outer_matrix():
for x in range(COLUMNS+1):
for y in range(ROWS+1):
ref = tk.Label(root,)#justify='center')
txt = None
if x == 0 and y != 0:
txt = y
top_bar.append(ref)
elif y == 0 and x != 0:
txt = x
sidebar.append(ref)
if txt != None or x == 0 and y == 0:
ref.config(text = txt, width=10)
ref.grid(row = y, column = x, sticky='nswe')
root.grid_columnconfigure(x,weight=1)
root.grid_rowconfigure(y,weight=1)
Full Example:
import tkinter as tk
ROWS = 6
COLUMNS = 6
top_bar = []
sidebar = []
def outer_matrix():
for x in range(COLUMNS+1):
for y in range(ROWS+1):
ref = tk.Label(root,)#justify='center')
txt = None
if x == 0 and y != 0:
txt = y
top_bar.append(ref)
elif y == 0 and x != 0:
txt = x
sidebar.append(ref)
if txt != None or x == 0 and y == 0:
ref.config(text = txt, width=10)
ref.grid(row = y, column = x, sticky='nswe')
root.grid_columnconfigure(x,weight=1)
root.grid_rowconfigure(y,weight=1)
else:
ref.destroy()
def inner_matrix():
for x in range(COLUMNS):
for y in range(ROWS):
ref = tk.Entry(inner_frame, width=10)
ref.grid(column=x,row=y, sticky='nswe')
inner_frame.grid_columnconfigure(x,weight=1)
inner_frame.grid_rowconfigure(y,weight=1)
ref.bind('<FocusIn>', lambda e:highlight(e))
ref.bind('<FocusOut>', lambda e:highlight(e))
def highlight(event):
info = event.widget.grid_info()
x_info = info['row']
y_info = info['column']
if 'FocusIn' in str(event):
top_bar[x_info].configure(bg='yellow')
sidebar[y_info].configure(bg='yellow')
if 'FocusOut' in str(event):
top_bar[x_info].configure(bg='SystemButtonFace')
sidebar[y_info].configure(bg='SystemButtonFace')
root = tk.Tk()
root.update()
inner_frame = tk.Frame(root,bg='red')
inner_frame.grid(row=1,column=1,
columnspan=COLUMNS,
rowspan = ROWS,
sticky = 'nswe')
outer_matrix()
inner_matrix()
root.mainloop()

How do I print the variable "new_text" in line in python

text_box is a tkinter text box
I am trying to convert source_text's letters to the number corresponding to the position of said letter
such that a or A = 1, b or B = 2 and print it the console
def enter():
#don't use 1 in place of 1.0
source_text=text_box.get(1.0, END)
def alphabet_position(text):
dict = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8','i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'}
new_text = text.lower(source_text)
for i in new_text:
if i in dict:
new_text = new_text.replace(i, dict[i])
print (new_text)
enter is called as such
btn = Button(root, text = "Enter", command = enter)
dict = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8','i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'}
new_text = text.lower()
for i in new_text:
if i in dict:
return new_text.replace(i, dict[i])
def enter():
print (alphabet_position(text_box.get(1.0, END)))

Issues with 2d array indexing python when making game

I'm attempting to program my own connect four game using Python. I'm trying to sort the circles that I have drawn into a 2d array. However when I try to assign my shape object to the array it gives me an index error. I can't really see an issue with counterrow and countrercolumn, can anyone else? Btw my space class just has an initialiser setting x1, x2, y1, y2, taken, and id
from tkinter import *
from space import *
master = Tk();
w = Canvas(master, width = 600, height = 500)
w.pack()
spaceList = []
for i in range(7):
spaceList.append([0] * 6)
currentmove = 'PLAYER1'
won = False
counterrow = 0
countercolumn = 0
for i in range(0,560,80):
for j in range(0,480,80):
w.create_oval(10+i, 10+j, 90+i, 90+j)
newspace = Space(10+i, 10+j, 90+i, 90+j, False, 'EMPTY')
spaceList[counterrow][countercolumn] = newspace
countercolumn = countercolumn + 1
counterrow = counterrow + 1
while(not won):
movecol = int(input("Please select a column!"))
def move(column):
for i in spaceList:
return 0
mainloop()
You have to reset the countercolumn:
for i in range(0,560,80):
# add this:
countercolumn = 0
for j in range(0,480,80):
# omitted
Otherwise it becomes seven and larger and you get an overflow.

How to pass a Tkinter Entry through a function

is there any reasonable way to convert my while loop into a for loop? I tried to create this, but I never got far cause the range's and/or xrange's broke because the number was too large or they don't take a float. Here's my while loop that I want to see if there is a reasonable for loop conversion for(This is within a function is why it's indented):
a = float(E1.get())
b = (a + 1)
c = sqrt(b)
e = sqrt(a)
f = (unichr(0x221A))
fractional, integral = modf(c)
while integral == integral:
fractional1, integral1 = modf(a / (integral**2))
print(fractional1)
if fractional1 != 0:
integral -= 1
continue
else: break
if a range or xrange is possible, it'd have to be range(1,a+1) or xrange(1,a+1)
This is my entire code:
def radical():
# Define variables needed
a = float(E1.get())
b = (a + 1)
c = sqrt(b)
e = sqrt(a)
f = (unichr(0x221A))
fractional, integral = modf(c)
while integral == integral:
fractional1, integral1 = modf(a / (integral**2))
print(fractional1)
if fractional1 != 0:
integral -= 1
continue
else: break
d = (a / (integral**2))
# make pointless floats integers
if integral.is_integer():
integral = int(integral)
if d.is_integer():
d = int(d)
if e.is_integer():
e = int(e)
# set conditions for output
if d == 1:
global master
master = Tkinter.Tk()
w = Tkinter.Message(master, padx=5, pady=5,text=(integral)).grid(ipadx=5, ipady=5)
master.title("Square Root")
master.mainloop()
elif integral == 1:
master = Tkinter.Tk()
w = Tkinter.Message(master, padx=5, pady=5,text=(f,d,"or",e)).grid(ipadx=5, ipady=5)
master.title("Simplified Radical")
master.mainloop()
else:
master = Tkinter.Tk()
w = Tkinter.Message(master, padx=5, pady=5,text=(integral,f,d,"or",e)).grid(ipadx=5, ipady=5)
master.title("Simplified Radical")
master.mainloop()
If you want infinite loop, you can use itertools.repeat(1) which will yield infinitely:
import itertools
....
for _ in itertools.repeat(1): # instead of `while integral == integral`
...
You can also use itertools.count() or itertools.cycle([1]).
UPDATE
Using range(integral, 0, -1), you can iterate from integral down to 1 (excluding 0).
for integral in range(integral, 0, -1): # xrange if you're using Python 2.x
fractional1, integral1 = modf(a / (integral**2))
print(fractional1)

Categories