I'm making a program using Tkinter where the user inputs their weight in Pound and then it outputs their weight in kilo.
I'm having problems getting the contents of the Entry from the user.
I'm calculating the pound to kilo in clicked1.
Can someone show me how I would get the Entry input there?
from Tkinter import *
import tkMessageBox
class App(object):
def __init__(self):
self.root = Tk()
self.root.wm_title("Question 7")
self.label = Label (self.root, text= "Enter your weight in pounds.")
self.label.pack()
self.entrytext = StringVar()
Entry(self.root, textvariable=self.entrytext).pack()
self.buttontext = StringVar()
self.buttontext.set("Calculate")
Button(self.root, textvariable=self.buttontext, command=self.clicked1).pack()
self.label = Label (self.root, text="")
self.label.pack()
self.root.mainloop()
def clicked1(self):
input = 3423 #I would like the user input here.
self.label.configure(text=input)
def button_click(self, e):
pass
App()
What you are looking for is [widget].get()
Text widget
In case you use the Text widget, you have to use [widget].get(1.0, END) where 1.0 means "first line, 0th character"
Code review
I've noticed a few other things in your code that could get improved:
PEP8 conformity; see pep8online.com
If you add a Shebang, Linux users will be able to execute it directly with ./script.py.
Variable naming:
input is a built-in function and you should avoid overwriting it
Use meaningful variable names (entrytext might be problematic in case you extend your program)
Avoid from Tkinter import *. This might lead to unexpected naming clashes.
Complete code
##!/usr/bin/env python
import Tkinter as Tk
class App(object):
def __init__(self):
self.root = Tk.Tk()
self.root.wm_title("Question 7")
self.label = Tk.Label(self.root, text="Enter your weight in pounds.")
self.label.pack()
self.weight_in_kg = Tk.StringVar()
Tk.Entry(self.root, textvariable=self.weight_in_kg).pack()
self.buttontext = Tk.StringVar()
self.buttontext.set("Calculate")
Tk.Button(self.root,
textvariable=self.buttontext,
command=self.clicked1).pack()
self.label = Tk.Label(self.root, text="")
self.label.pack()
self.root.mainloop()
def clicked1(self):
weight_in_kg = self.weight_in_kg.get()
self.label.configure(text=weight_in_kg)
def button_click(self, e):
pass
App()
Is this the kinda thing you are looking for?
from Tkinter import *
import tkMessageBox
class App(object):
def __init__(self):
self.root = Tk()
self.root.wm_title("Question 7")
self.label = Label (self.root, text= "Enter your weight in pounds.")
self.label.pack()
self.entrytext = StringVar()
Entry(self.root, textvariable=self.entrytext).pack()
self.buttontext = StringVar()
self.buttontext.set("Calculate")
Button(self.root, textvariable=self.buttontext, command=self.clicked1).pack()
self.label = Label (self.root, text="")
self.label.pack()
self.root.mainloop()
def clicked1(self):
input = self.entrytext.get()
result = int(input)*2
self.label.configure(text=result)
def button_click(self, e):
pass
App()
I think this is what your'e looking for, although not just times by 2.
You would probably also want to put in an exception for if the value is not a int.
As you have associated a StringVar with your Entry widget, you can easily access/manipulate the widget's text with StringVar's get and set methods.
See here for more information.
Related
I have several simpledialog popup windows. The first one that shows is in focus and after it closes then every single one after that is not in focus. The simpledialog code is this:
from tkinter import *
from tkinter import messagebox
import os
import tkinter as tk
from tkinter import simpledialog
def doing_stocks():
name = myaskstring("Input data", "Enter box number:", parent = root)
name2 = myaskstring("Input data2", "Enter box number2:", parent = root)
name3 = myaskstring("Input data3", "Enter box number3:", parent = root)
class My_QueryString(tk.simpledialog._QueryString):
def body(self, master):
self.bind('<KP_Enter>', self.ok)
self.bind('<Return>', self.ok)
w = Label(master, text=self.prompt, justify=LEFT)
w.grid(row=0, padx=5, sticky=W)
self.entry = Entry(master, name="entry")
self.entry.grid(row=1, padx=5, sticky=W+E)
if self.initialvalue is not None:
self.entry.insert(0, self.initialvalue)
self.entry.select_range(0, END)
root.update_idletasks()
self.entry.focus_force()
return self.entry
def myaskstring(title, prompt, **kw):
d = My_QueryString(title, prompt, **kw)
root.update_idletasks()
answer = d.result
d.destroy()
return answer
root = Tk()
root.geometry("700x761")
label1 = Label(root, text="")
label1.place(x = 0, y = 0)
button2 = Button(root, text = "Doing Stocks", command=doing_stocks).place(x = 300, y = 340)
root.mainloop()
This is a simplified version of the code. I call my simpledialog popups like this:
myaskstring("Title", "Prompt", parent = root)
In the doing_stocks() method the first time I call myaskstring the window and the entry field will be in focus then all times after that it won't be. How can I make every simpledialog be in focus when it appears on the screen?
I agree is seems odd that the focus isn't set to each My_QueryString instance when it's initialized. Regardless of the reason why, a workaround for it not happening is to bind a <Map> event handler function to the dialog's Entry widget to shift keyboard focus to itself whenever it's made visible.
The code below shows an implementation doing that. It's based on your code with the important changes indicated with # ALL CAP comments to make them stand out.
import tkinter as tk
from tkinter import simpledialog
from tkinter.constants import *
def doing_stocks():
name = myaskstring("Input data", "Enter box number:", parent=root)
name2 = myaskstring("Input data2", "Enter box number2:", parent=root)
name3 = myaskstring("Input data3", "Enter box number3:", parent=root)
class My_QueryString(tk.simpledialog._QueryString):
def body(self, master):
self.bind('<KP_Enter>', self.ok)
self.bind('<Return>', self.ok)
w = tk.Label(master, text=self.prompt, justify=LEFT)
w.grid(row=0, padx=5, sticky=W)
self.entry = tk.Entry(master, name="entry")
self.entry.grid(row=1, padx=5, sticky=W+E)
self.entry.bind('<Map>', self.on_map) # <--- ADDED.
if self.initialvalue is not None:
self.entry.insert(0, self.initialvalue)
self.entry.select_range(0, END)
root.update_idletasks()
# self.entry.focus_force() # <--- NOT NEEDED.
return self.entry
# ADDED METHOD.
def on_map(self, event):
self.entry.focus_force()
def myaskstring(title, prompt, **kw):
d = My_QueryString(title, prompt, **kw)
root.update_idletasks()
answer = d.result
# d.destroy() # <--- NOT NEEDED.
return answer
root = tk.Tk()
root.geometry("700x761")
label1 = tk.Label(root, text="")
label1.place(x = 0, y = 0)
button2 = tk.Button(root, text = "Doing Stocks", command=doing_stocks)
button2.place(x = 300, y = 340)
root.mainloop()
Learning to use Tkinter and following an online tutorial. This is an example given where text is entered and then label will update accordingly to the input text field.
I'm trying it in Python3 on Mac and on Raspberry Pi and I don't see the effect of trace, hence the label doesn't get modified by the Entry. Any help would be appreciate (or any other simple example of how to use Entry and Trace together)
Thanks.
from tkinter import *
class HelloWorld:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(
frame, text="Hello", command=self.button_pressed
)
self.button.pack(side=LEFT, padx=5)
self.label = Label(frame, text="This is a label")
self.label.pack()
a_var = StringVar()
a_var.trace("w", self.var_changed)
self.entry = Entry(frame,textvariable=a_var)
self.entry.pack()
def button_pressed(self):
self.label.config(text="I've been pressed!")
def var_changed(self, a, b, c):
self.label.config(text=self.entry.get())
def main():
root = Tk()
root.geometry("250x150+300+300")
ex = HelloWorld(root)
root.mainloop()
if __name__ == '__main__':
main()
The problem is that you are using a local variable for a_var, and on the Mac it is getting garbage-collected. Save a reference to the variable (eg: self.a_var rather than just a_var).
self.a_var = StringVar()
self.a_var.trace("w", self.var_changed)
self.entry = Entry(frame,textvariable=self.a_var)
self.entry.pack()
Note: if all you want is to keep a label and entry in sync, you don't need to use a trace. You can link them by giving them both the same textvariable:
self.entry = Entry(frame, textvariable=self.a_var)
self.label = Label(frame, textvariable=self.a_var)
I am trying to retrieve the word before everytime space is entered. For example, If a user types " iam a" i want to retrieve "iam" and then if user types "iam a girl" i want to retrieve "a" .
Following is my code:
import tkinter as tk
import time
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
lsum = tk.Label(self,borderwidth=2,text="suggestions")
lsum.grid(row=2, column=5, sticky=tk.W)
def func3():
contents = self.text.get("1.0", tk.END)
lsum["text"] = contents
def func4():
self.text.bind("<space>",func3())
self.text= tk.Text(self, height=5, width=30,borderwidth=2)
self.text.pack(side=tk.RIGHT)
self.text.grid(row=0, column=4)
self.text.insert(tk.END, "")
self.v = tk.IntVar()
self.d = tk.IntVar()
self.e = tk.IntVar()
self.radio1=tk.Radiobutton(self, text="آيک گرآم مآڈل ", variable=self.v, value=1,command=func2).grid(column=0,row=1,columnspan=2)
self.radio2=tk.Radiobutton(self, text="دو گرآم مآڈل ", variable=self.d, value=2,command=func3).grid(column=0,row=2,columnspan=2)
self.radio3=tk.Radiobutton(self, text="تین گرآم مآڈل", variable=self.e, value=3).grid(column=0,row=3,columnspan=2)
if __name__ == '__main__':
run = ExampleApp()
run.mainloop()
Kindly Help please.
Assuming that I understand what you're asking (which is tricky enough) you can call .bind() on the Text widget with the event being "<space>".
This would look something like the below:
from tkinter import *
root = Tk()
text = Text(root)
text.pack()
def callback(*args):
print(text.get("1.0", END).split(" ")[len(text.get("1.0", END).split(" "))-1])
text.bind("<space>", callback)
root.mainloop()
This means that everytime the space key is pressed in the Text widget we get a callback which prints the word you're looking for in the widget.
from tkinter import *
import random
root = Tk()
name = StringVar()
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("Are you smart enough?")
self.pack(fill=BOTH, expand="no")
self.entry = Entry(root,textvariable=name)
self.entry.pack()
enterButton = Button(self, text="Enter", command=self.client_enter)
enterButton.pack(side="top", fill="none", expand="True", anchor = "s")
def client_enter(self):
text = name.get()
textlabel = Label(self, text=name).pack()
app = Window(root)
root.geometry("1200x600")
root.mainloop()
For some reason, when I input a name and press the "Enter" button, nothing shows up.
How can I make it say ("Welcome", name) on Tkinter?
It seems like the variable text contains the right value, but you are displaying the name (which is a StringVar) instead.
Replace this:
textlabel = Label(self, text=name).pack()
By this:
textlabel = Label(self, text=text).pack()
To make it say "Welcome, name", change the definition of text as such:
text = "Welcome, {}".format(name.get())
Also, textlabel becomes useless if you put .pack() in its definition. You should be doing it like this:
textlabel = Label(self, text=text)
textlabel.pack()
Or like this if you don't need to store it in a variable:
Label(self, text=text).pack()
So I am currently trying to create a button on a GUI that will let the user generate a new entry field.
I have no idea how to do this. I'm guessing that it will require a lambda function, but apart from that, I have no idea.
Here's the basic code I have so far:
from tkinter import *
class prac:
def autoAddWidget(self,frame,x,y):
self.entryField = Entry(frame,text="Entry Field")
self.entryField.grid(row=x, column=y)
#lambda function?
def __init__(self, master):
frame = Frame(master, width=60, height=50)
frame.pack()
x=1
self.addWidgetButton = Button(frame, text="Add new widget", command=self.autoAddWidget(frame, x,0))
self.addWidgetButton.grid(row=0, column=0)
x+=1
root = Tk()
app = prac(root)
root.mainloop()
Would appreciate the help.
Thanks
You're passing to the command argument result from the method self.autoAddWidget(frame, x,0) not method itself. You have to pass there a reference to a callable object, a function that will be called when the event occurs. Please check a documentation next time before you ask the question.
Ok, I fixed the code, now it works:
from tkinter import *
class Prac:
def autoAddWidget(self):
self.entryField = Entry(self.frame,text="Entry Field")
self.entryField.grid(row=self.x, column=0)
self.x+=1
def __init__(self, master):
self.frame = Frame(master, width=60, height=50)
self.frame.pack()
self.x=1
self.addWidgetButton = Button(self.frame, text="Add new widget", command=self.autoAddWidget)
self.addWidgetButton.grid(row=0, column=0)
root = Tk()
app = Prac(root)
root.mainloop()