I am trying to retrieve a variable from a Tkinter Wiget but I am running into this error message:
AttributeError: 'int' object has no attribute 'get'
Here is the widget code
JobNEntry = tkinter.Entry(menu, textvariable = tk.IntVar(JobNo))
JobNEntry.grid(row=2, column=2, sticky="W")
Here is the call code
JobNo=JobNo.get()
Also I need to know if the variable JobNo is writable to a file.
Thanks in advance
The get() method is part of several widgets in tkinter and is not something that you can use on a normal int or str object. get() must be called on a variable that is a widget object that has a get() method, like Entry.
Its likely you need to do:
JobNEntry.get()
This will get the current value from the entry field as a string.
If you want to save the value of that string you can. There are several tutorials on Stack Overflow and the web that go into detail on how to save a string to a file.
Looking at the code you have shown us, it's possible you have not created your IntVar() correctly.
Make sure you define the IntVar() first then set that variable as the textvariable.
Something like this:
JobNo = tk.IntVar()
JobNEntry = tkinter.Entry(menu, textvariable = JobNo)
The attribute error might be because you havnt already initialized the variable JobNo as an 'IntVar'
This is the code i have come up with :
import tkinter as tkinter
menu=tkinter.Tk()
JobNo=tkinter.IntVar()
JobNEntry = tkinter.Entry(menu, textvariable = JobNo)
JobNEntry.grid(row=2, column=2, sticky="W")
JobNo=JobNo.get()
menu.mainloop()
You need to initialize JobNo as an Integer Variable using IntVar()
JobNo=tkinter.IntVar()
And then use it in the Entrybox.
If you had some string to add to the entry, you should initialise as StringVar()
Also when you initialize, make sure you do it after opening the Tk window.(here i put it after menu=tkinter.Tk())
Something like this:
from tkinter import *
from tkinter import ttk
def save_job_no():
try:
n = job_no.get()
except TclError:
status.config(text = "This is not an integer")
return False
status.config(text="")
f = open("my_file.txt", "w")
f.write(str(n))
return True
root = Tk()
job_no = IntVar()
entry = ttk.Entry(root, width = 30, textvariable = job_no)
entry.grid()
label = ttk.Label(root, textvariable = job_no)
label.grid()
status = ttk.Label(root)
status.grid()
button = ttk.Button(root, text = "Write to a file", command = save_job_no)
button.grid()
root.mainloop()
Related
I want to use the input value as variable and this is my code.
from tkinter import *
from tkinter import messagebox
window = Tk()
Label(window, text='Cavity number').grid(row=0)
CavNum = StringVar()
for i in range(1,8) :
globals()['L{}_CavNum'.format(i)] = StringVar()
globals()['L{}_CavNum'.format(i)] = Entry(window, textvariable=globals()['L{}_CavNum'.format(i)])
globals()['L{}_CavNum'.format(i)].grid(row=0, column=i)
window.geometry("1200x150")
window.mainloop()
everytime I do print(L1_CavNum), it says "<tkinter.Entry object .!entry>". please tell me what is the problem
You are re-using the same name for the entry widget as you use for StringVar. You could simply change globals()['L{}_CavNum'.format(i)] = StringVar() to globals()['L{}_CavNumSV'.format(i)] = StringVar() and print(L1_CavNum) to print(L1_CavNumSV.get()). However the .get() function will execute when your code runs so you will have to have a button or another event to callback the function.
I would do it like this.
from tkinter import *
def print_vars():
for x in range(len(cavity_string_vars)):
print(cavity_string_vars[x].get())
window = Tk()
Label(window, text='Cavity number').grid(row=0)
cavity_string_vars = []
cavity_entries = []
for i in range(7):
cavity_string_vars.append(StringVar())
cavity_entries.append(Entry(window, textvariable=cavity_string_vars[i]))
cavity_entries[i].grid(row=0, column=i)
print_button = Button(window, text="Print", command=print_vars)
print_button.grid(row=1, column=0)
window.geometry("1200x150")
window.mainloop()
To me associated arrays are much easier than naming each variable even when you program it as you have. Perhaps that is needed for your case.
Is there a way to access variables from different files if the widget is an Entry? I have tried using the command option but found that was exclusive to Buttons. I'm trying to separate my functions into different files to modulate.
ttk.Label(root, text="How many points do you want to input:").pack()
cell_content = StringVar()
cell_content.trace_add("write", my_tk.retrieve_cell_content)
cell_content_entry = Entry(root, width = 8, textvariable = cell_content)
cell_content_entry.pack()
tkinterFunctions.py
def retrieve_cell_col(self, *args):
global CELL_COL
temp = cell_col.get()
temp = temp.upper()
If I get it right, you want to get your text in Entry widget when it is writing. Not by pushing a Button. please check this if I am right:
from tkinter import *
def call(tex):
print(tex.get())
root = Tk()
tx = StringVar()
tx.trace("w", lambda name, index, mode, tex=tx: call(tex))
entry = Entry(root, textvariable=tx)
entry .pack()
root.mainloop()
I have written a code in python 2.7 which implements "optionmenu" widget. I am facing a problem that i have given six values in the tuple but when i select another option rather than "Gmail", i see only five values in the dropdown. can anyone tell me my mistake?
from Tkinter import *
import ttk
root = Tk()
choices = ("Gmail", "Outlook/Hotmail", "Yahoo", "Comcast", "AT&T", "Verizon")
dropdown_var = StringVar()
dropdown_var.set(choices[0]) # set default value
def data(*args):
value = dropdown_var.get()
print(value)
l = ttk.Label(root, text="Select your e-mail provider : ")
l.pack(side="left")
option = ttk.OptionMenu(root, dropdown_var, *choices)
option.pack(side="left", padx=10, pady=10)
b = ttk.Button(root, text="Click", command=data)
b.pack(side="bottom")
root.mainloop()
The issue you're facing is linked to the way you are defining the OptionMenu widget.
In fact, it's different from the tkinter OptionMenu because you set the default value inside the declaration. So when you unpack the values, the first index "Gmail" is taken as the default parameter for the widget, and the others are the options values.
(In addition, you don't need to set dropdown_var before)
Try this version :
choices = ("Gmail", "Outlook/Hotmail", "Yahoo", "Comcast", "AT&T", "Verizon")
dropdown_var = StringVar()
def data(*args):
value = dropdown_var.get()
print value # no bracket for python2
l = ttk.Label(root, text="Select your e-mail provider : ")
l.pack(side="left")
# the 3rd parameter is the default value
option = ttk.OptionMenu(root, dropdown_var, choices[0], *choices)
option.pack(side="left", padx=10, pady=10)
I've got a program that counts clicks of a button and displays them on a label. Instead of just showing the number, how can I add "Number of clicks: " before the value displayed? Preferably within the Label's widget arguments/options where textvariable=Total is defined.
Total = IntVar()
def Clicked():
Total.set(Total.get() + 1)
total = Label(root, textvariable=Total).pack()
click = Button(root, command=Clicked).pack()
Use separate variables to keep track of the number of clicks, and the string that represents the number of clicks.
from Tkinter import *
def Clicked():
global amount
amount += 1
Total.set("Number of clicks: {}".format(amount))
root = Tk()
Total = StringVar()
amount = 0
Label(root, textvariable=Total).pack()
Button(root, command=Clicked).pack()
root.mainloop()
Incidentally, never pack a widget and assign it to something on the same line - your variable will always be None. See Tkinter: AttributeError: NoneType object has no attribute get for more information.
tkinter requires that you use its own variable types for textvariable, so I would use a StringVar as your textvariable (you can update the text property of some items directly, but different tkinter objects may have different methods for doing this, and it can get confusing). Here's how you can update a StringVar to show your counts.
root = tk.Tk()
tk.IntVar(value='1')
sv = tk.StringVar()
sv.set('clicks = ' + str(iv.get()))
>>> sv.get()
'clicks = 1'
Here is the below code and I am having issues surrounding retrieving input from multiple values. I have been working on this issue for some time now without any suggest. I do appreciate the insight; however, I am at wits end. If someone could please provide a fix to my code I would be ever so grateful.
#!C:/Python27/python.exe
from Tkinter import *
import ImageTk, Image
root = Tk()
root.title('HADOUKEN!')
def retrieve_input(text,chkvar,v):
textarea_result = text.get()
checkbox_result = chkvar.get()
radiobutton_result = v.get()
root.destroy()
text = Text(root, height=16, width=40)
scroll = Scrollbar(root, command=text.yview)
text.configure(yscrollcommand=scroll.set)
text.grid(sticky=E)
scroll.grid(row=0,column=1,sticky='ns')
text.focus()
chkvar = IntVar()
chkvar.set(0)
c = Checkbutton(root, text="CaseIt", variable=chkvar)
c.grid(row=1,column=0,sticky=W)
v = ""
radio1 = Radiobutton(root, text="Src", variable=v, value=1)
radio1.grid(row=1,column=0)
radio1.focus()
radio2 = Radiobutton(root, text="Dst", variable=v, value=2)
radio2.grid(row=2,column=0)
b1 = Button(root, text="Submit", command=lambda: retrieve_input(text,chkvar,v))
b1.grid(row=1, column=2)
img = ImageTk.PhotoImage(Image.open("Hadoken.gif"))
panel = Label(root, image = img)
panel.grid(row=0, column=2)
root.mainloop()
print textarea_result
print checkbox_result
print radiobutton_result
You have several problems in your code, though most of them produce errors that should be self-explanatory. My suggestion is to start over with just a single widget, and get the logic working for that to reduce the number of things that could go wrong. Once you have that working, you can then add one widget at a time as you learn how to use that widget.
That being said, here are the most obvious errors that I spotted:
The first problem is that you are incorrectly calling the get method of a text widget. This method is documented to take two arguments -- a starting index and an ending index. Since tkinter always adds a trailing newline, you want to get everything from the start ("1.0"), to the end minus one character ("end-1c"). Thus, you should be getting the value in the text widget like this:
textarea_result = text.get("1.0", "end-1c")
The second problem is that retrieve_input seems to assume that v is a StringVar or IntVa since you are calling a get method on it. Given that you are using that variable with a radiobutton, that's what it should be. However, you created it as a normal variable, which of course doesn't have a get method. You should declare it as one of the special tkinter variables:
...
v = StringVar()
radio1 = Radiobutton(root, text="Src", variable=v, value=1)
...
The third problem is, retrieve_input is setting local variables. If you want to set the value of global variables (which I assume, since you are later trying to access them after the widget is destroyed), then you need to declare them as global:
def retrieve_input(text,chkvar,v):
global textarea_result, checkbox_result, radiobutton_result
...