Python - Display Entered text in tkinter - python

I'm trying to write a simple Tkinter form. It should read user's input, and then display the result when clicking a button.
However, my code doesn't return anything. I found this thread:
Python Tkinter Entry get()
But still nothing I do returns me the text that users entered.
This is my script. Your help is appreciated:
import tkinter as tk
import tkinter.font as tkFont
class App:
def __init__(self, root):
# setting title
root.title("undefined")
# setting window size
global result
width = 600
height = 500
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
LineEdit = tk.Entry(root)
LineEdit["borderwidth"] = "2px"
LineEdit.place(x=250, y=50, width=289, height=30)
result = LineEdit.get()
LineLabel = tk.Label(root)
LineLabel["text"] = "Enter Your Input:"
LineLabel.place(x=60, y=50, width=177, height=30)
GoButton = tk.Button(root)
GoButton["text"] = "Analyze"
GoButton.place(x=170, y=130, width=195, height=58)
GoButton["command"] = self.DisplayInput
def DisplayInput(self):
print(result)
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
root.mainloop()

You should get the content of LineEdit inside DisplayInput(). But you need to change LineEdit to instance variable self.LineEdit, otherwise it cannot be accessed inside DisplayInput():
import tkinter as tk
import tkinter.font as tkFont
class App:
def __init__(self, root):
# setting title
root.title("undefined")
# setting window size
#global result
width = 600
height = 500
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
self.LineEdit = tk.Entry(root)
self.LineEdit["borderwidth"] = "2px"
self.LineEdit.place(x=250, y=50, width=289, height=30)
#result = LineEdit.get()
LineLabel = tk.Label(root)
LineLabel["text"] = "Enter Your Input:"
LineLabel.place(x=60, y=50, width=177, height=30)
GoButton = tk.Button(root)
GoButton["text"] = "Analyze"
GoButton.place(x=170, y=130, width=195, height=58)
GoButton["command"] = self.DisplayInput
def DisplayInput(self):
result = self.LineEdit.get()
print(result)
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
root.mainloop()

Related

Multiple frames within Tkinter

I am experimenting with Tkinter to build a simple UI. This will contain a similar structure to the below:
Menu
Settings
Action1
Etc...
I want Menu to be my main frame, and there to be some general stuff on there and then buttons to the other frames.
I have been using some code I found here as a baseline but my amendments failed to work as expected. For example, why do the Label's and Entry's I place not show?
Code is as follows:
import tkinter as tk
def raise_frame(frame):
frame.tkraise()
root = tk.Tk()
root.title("Name")
width=400
height=500
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
f1 = tk.Frame(root)
f2 = tk.Frame(root)
f3 = tk.Frame(root)
f4 = tk.Frame(root)
title = tk.Label(f1, text = "Title", background = '#3b5997', foreground ="white", font = ("Times New Roman", 25))
title.place(x=100,y=20,width=200,height=50)
eg1 = tk.Label(f1, text="Text :")
eg1.place(x=10,y=195,width=70,height=25)
eg2 = tk.Label(f1, text="Text")
eg2.place(x=290,y=195,width=70,height=25)
eg3 = tk.Entry(f1, width=20)
eg3.place(x=100,y=195,width=200,height=25)
raise_frame(f1)
root.mainloop()
I have used .grid() and pack() but never used place however I found the issue.
you need to use .place() for frame f1 as well, after the content that you want in that frame.
import tkinter as tk
def raise_frame(frame):
frame.tkraise()
root = tk.Tk()
root.title("Name")
width=400
height=500
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
f1 = tk.Frame(root)
f2 = tk.Frame(root)
f3 = tk.Frame(root)
f4 = tk.Frame(root)
title = tk.Label(f1, text = "Title", background = '#3b5997', foreground ="white", font = ("Times New Roman", 25))
title.place(x=100,y=20,width=200,height=50)
eg1 = tk.Label(f1, text="Text :")
eg1.place(x=10,y=195,width=70,height=25)
eg2 = tk.Label(f1, text="Text")
eg2.place(x=290,y=195,width=70,height=25)
eg3 = tk.Entry(f1, width=20)
eg3.place(x=100,y=195,width=200,height=25)
f1.place(x=100,y=20,width=1000,height=900) # <-------------like this
raise_frame(f1)
root.mainloop()

Encountering issues with button switches in PyCharm GUI

I have been trying to implement a GUI with PyCharm and would like to be able to use multiple switches as seen in the code below. Unfortunately, the switches only seem to work 1 at a time while the other 1 doesn't do anything when clicked on. Is there any way we can make both of them work while being in the same code?
Also, as it appears the black background is only active after the switch image has been clicked at least once. Is there any way to make the black background active by default?
import tkinter
from tkinter import *
import tkinter.font as tkFont
from PIL import ImageTk, Image
import serial
import time
import os
root = Tk()
root.config(bg='black')
rootWidth = root.winfo_screenwidth()
rootHeight = root.winfo_screenheight()
switch_variable = tkinter.StringVar(value="off")
global is_on
is_on = True
switch_variable2 = tkinter.StringVar(value="reverse2")
global is_forward
is_forward = True
# This part of the code allows constant font size for all monitor screens
normalWidth = 1920
# Width of monitor screen used to write this code
normalHeight = 1080
# Height of monitor screen used to write this code
percentWidth = rootWidth / (normalWidth / 100)
percentHeight = rootHeight / (normalHeight / 100)
scale = ((percentWidth + percentHeight) / 2) / 100
fontstyle = tkFont.Font(family='Cambria', size=50)
def switch():
global is_on
if is_on:
on_button.config(image=on, bg='black', bd=0, activebackground='black', command=switch)
is_on = False
else:
on_button.config(image=off, bg='black', bd=0, activebackground='black', command=switch)
is_on = True
def switch2():
global is_forward
if is_forward:
forward_button.config(image=forward2, bg='black', bd=0, activebackground='black', command=switch2)
is_forward = False
else:
reverse_button.config(image=reverse2, bg='black', bd=0, activebackground='black', command=switch2)
is_forward = True
forward2 = Image.open("C:/Users/LattePanda/Desktop/images/LedOn.png")
reverse2 = Image.open("C:/Users/LattePanda/Desktop/images/LedOff.png")
on = Image.open("C:/Users/LattePanda/Desktop/images/forward.png")
off = Image.open("C:/Users/LattePanda/Desktop/images/reverse.png")
resizeOn = on.resize((600,600),Image.ANTIALIAS)
resizeOff = off.resize((600,600),Image.ANTIALIAS)
resizeOn2 = forward2.resize((400,400),Image.ANTIALIAS)
resizeOff2 = reverse2.resize((400,400),Image.ANTIALIAS)
on = ImageTk.PhotoImage(resizeOn)
off = ImageTk.PhotoImage(resizeOff)
forward2 = ImageTk.PhotoImage(resizeOn2)
reverse2 = ImageTk.PhotoImage(resizeOff2)
on_button = Button(root,image=on, bd=0,activebackground='black',command=switch)
on_button.pack(pady=50)
off_button = Button(root,image=off, bd=0,activebackground='black',command=switch)
forward_button = Button(root,image=forward2, bd=0,activebackground='black',command=switch2)
forward_button.pack(pady=50)
reverse_button = Button(root,image=reverse2,bd=0,activebackground='black',command=switch2)
master=tkinter.Tk()
master.title("place() method")
master.geometry("450x350")
master.mainloop()
root.after(0, update, 0)
root.mainloop()
on_button.pack(pady=50)
label_on = Label(root, text="LED: ON",image=on,activebackground='black',height=400,width=400)
label_on.pack(padx=100,pady=50)
label_off = Label(root, text="LED: OFF",image=off,activebackground='black',height=400,width=400)
label_off.pack(padx=50,pady=50)
forward_button.pack(pady=50)
label_forward = Label(root, text="Forward",image=forward,activebackground='black',height=500,width=500)
label_forward.pack(padx=100,pady=50)
label_reverse = Label(root, text="Reverse",image=reverse,activebackground='black',height=500,width=500)
label_reverse.pack(padx=50,pady=50)
#switch_frame.pack()
root.mainloop()

canvas not display image after I call the function from another python file

I have two files:
mainfile.py : have button when I click on it should call the another file(showfile.py) which have function that contain canvas image , but nothing loaded ..
mainfile.py
from tkinter import *
import tkinter as tk
from showfile import sho
class Window(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master, bg='#333333')
menu = tk.Menu(self.master)
master.config(menu=menu)
root.minsize(width=1080, height=750)
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry('%dx%d+0+0' % (width, height))
root.iconbitmap("p.ico")
full = Button(root, text="Full Screen", command=sho, padx=10, pady=10, borderwidth=6)
full.pack(pady=20)
full.place(x=100, y=500)
root = Tk()
root.geometry("%dx%d" % (300, 300))
root.title("BMP Image GUI")
app = Window(root)
app.pack(fill=tk.BOTH, expand=1)
root.mainloop()
showfile.py
from tkinter import *
from PIL import ImageTk, Image
import tkinter as tko
def sh():
lan = tko.Tk() # Creating instance of Tk class
lan.title("Centering windows")
lan.resizable(False, False) # This code helps to disable windows from resizing
window_height = 300
window_width = 500
screen_width = lan.winfo_screenwidth()
screen_height = lan.winfo_screenheight()
x_cordinate = int((screen_width / 2) - (window_width / 2))
y_cordinate = int((screen_height / 2) - (window_height / 2))
lan.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate, y_cordinate))
filename = "iy.jpg"
load = Image.open(filename)
w, h = load.size
image = filename
render2 = ImageTk.PhotoImage(load) # must keep a reference to this
lastwidth, lasthight = w,h
image = load.resize((int(lastwidth), int(lasthight)), Image.ANTIALIAS)
canvas2 = tko.Canvas(lan,width=lastwidth, height=lasthight)
canvas2.pack(fill=tko.BOTH, expand=True)
canvas2.pack()
canvas2.place(relx=0.5, rely=0.5, anchor=CENTER)
render2 = ImageTk.PhotoImage(image)
canvas2.create_image(lastwidth / 2, lasthight / 2, image=render2, anchor=CENTER)
render2 = ImageTk.PhotoImage(load)
but when I run this files ,,, it popup without loaded image ,, and give error : _tkinter.TclError: image "pyimage1" doesn't exist

Cannot make a label wider

I have this reproducible code, and I cannot understand why when I set the width value to 100 in the self.display_tcm_18 variable, it still does not increase its width. This self.display_tcm_18 lies within the self.xf Frame, which I set to a width value of 300 (wide enough to host a Label widget of 100). I don't know what I am missing in the Logic of building this GUI with tkinter. Does anyone could give me some hint?
import Tkinter
from Tkinter import *
import tkFileDialog
from tkFileDialog import askopenfilename
from tkFileDialog import askdirectory
class Window(Frame):
def __init__(self, master = None):
self.master = master
path = "logo.gif"
self.image = Tkinter.PhotoImage(file=path)
self.f = Frame(master, width=300, height =70)
self.sf = Frame(master, width=300, height=70)
self.xf = Frame(self.f,width = 300, relief=GROOVE, borderwidth = 2)
self.file_name_18 = ''
self.var = IntVar()
def browse_button():
filename = askopenfilename(filetypes = (("GEOTIFF Files", "*.tif"),))
self.file_name = filename
self.display.config(text = filename)
print(self.file_name)
self.Logo = Label(self.master, image = self.image).pack(side=TOP, padx=5)
self.open_tcm_button = Button(self.xf, text = "Open..", command = browse_button).pack(side=LEFT, padx = 5, pady = 10)
self.display_tcm_18 = Label(self.xf, width = 100, bg = "white", textvariable = self.file_name_18, relief = SUNKEN, anchor = W)
self.display_tcm_18.pack(side=LEFT)
self.tcm18_label = Label(self.f, text = "Tree Cover Mask 2018 ").place(relx=0.06, rely=0.125,anchor=W)
self.xf.place(relx=0.01, rely=0.125, anchor=NW)
self.f.pack(side=TOP)
root = Tk()
root.geometry("600x400")
app = Window(root)
root.mainloop()

canvas command not working inside function

Help! I am using python 3.5.2 and the function self.new_game is not working. It is supposed to put text on the canvas but it does nothing! There are also no errors that appear in the shell.
from tkinter import *
import time
import os
WIDTH = 1920
HEIGHT = 1080
root = Tk()
root.state('zoomed')
planet_selected = 0
planet_name = "nothing"
planet_temp = -270
planet_size = 0.0
planet_life = 0.0
class Space(Frame):
def __init__(self):
Frame.__init__(self)
frame1 = Frame(self)
self.canvas = Canvas(frame1, width = WIDTH, height = HEIGHT, bg ="white")
self.canvas.focus_set()
self.canvas.create_text(1920,1000,text='Planetary Creator',font=('Arial',15))
self.master.title("Planetary Creator Alpha 0.1")
frame = Frame(root, bg='grey', width=1920, height=40)
frame.pack(fill='x')
button1 = Button(frame, text='New Game',command=lambda : self.new_game())
button1.pack(side='left', padx=10)
button2 = Button(frame, text='Quit Game',command=lambda : os._exit(0))
button2.pack(side='left')
#this function below does not work!!!
def new_game(self):
self.canvas.delete(ALL)
size = self.canvas.create_text(960,540,text=str(planet_size) + "moon",font=("Arial",10))
life = self.canvas.create_text(960,520,text="✣" + str(planet_life) + "%",font=("Arial",10))
temp = self.canvas.create_text(960,500,text=str(planet_temp) + "°C",font=("Arial",10))
name = self.canvas.create_text(960,480,text=planet_name,font=("Arial",15))
Space().mainloop()
I removed frame1 and put Canvas in root , and use canvas.pack() to see canvas in window.
(but I could use self instead of root and use self.pack() because Space inherits from Frame. it would ne more logical)
After that I had to only change text positions because windows was too big for my screen.
I used variables CENTER_X, CENTER_Y to put text in center regardless of the size of the screen.
from tkinter import *
import time
import os
class Space(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.master.title("Planetary Creator Alpha 0.1")
self.canvas = Canvas(root, width=WIDTH, height=HEIGHT, bg="white")
self.canvas.pack()
self.canvas.focus_set()
self.canvas.create_text(CENTER_X, CENTER_Y, text='Planetary Creator', font=('Arial',15))
frame = Frame(root, bg='grey', width=WIDTH, height=40)
frame.pack(fill='x')
button1 = Button(frame, text='New Game', command=self.new_game)
button1.pack(side='left', padx=10)
button2 = Button(frame, text='Quit Game', command=root.destroy)
button2.pack(side='left')
def new_game(self):
self.canvas.delete(ALL)
size = self.canvas.create_text(CENTER_X, CENTER_Y, text=str(planet_size) + "moon", font=("Arial",10))
life = self.canvas.create_text(CENTER_X, CENTER_Y-20, text="✣" + str(planet_life) + "%", font=("Arial",10))
temp = self.canvas.create_text(CENTER_X, CENTER_Y-40, text=str(planet_temp) + "°C", font=("Arial",10))
name = self.canvas.create_text(CENTER_X, CENTER_Y-60, text=planet_name, font=("Arial",15))
# --- main ---
WIDTH = 800 #1920
HEIGHT = 500 #1080
CENTER_X = WIDTH//2
CENTER_Y = HEIGHT//2
planet_selected = 0
planet_name = "nothing"
planet_temp = -270
planet_size = 0.0
planet_life = 0.0
root = Tk()
#root.state('zoomed')
Space(root)
root.mainloop()

Categories

Resources