I have a simple script to convert Degree Minute Second to Decimal Degree, using tkinter with a simple GUI. The script waits for the user to click the "Calculate" button before proceeding, to ensure values have been entered in the required 'tk.Entry' fields, then displays the calcuated output.
How would I implement a "Reset" button to allow for another calculation to be run?
I was thinking a while loop for my entire script but don't understand how to implement it.
Apologies for the elementary question, this is my first attempt at using tkinter / GUI, it was much easier to add a re-run while loop to the commandline version of my script.
edit: the "Reset" button currently does nothing, it's just for placement.
# Check python version and import correct tkinter.
import string
import sys
if (sys.version_info.major == 3):
print("Python 3")
import tkinter as tk# for Python 3
else:
print("Python 2")
import Tkinter as tk# for Python 2.7
# Configure tkinter window name, size, colour, columns.
root = tk.Tk()
root.title("CCT")
root.resizable(False, False)
root.attributes("-alpha", 0.95)
root.config(bg = "#F5F5F5")
# Label for top of application.
label_info = tk.Label(root, text="Coordinate Conversion Tool", pady = 5, bg = "#e8e8e8", padx=10)
label_info.grid(row=0, column=0, columnspan=4, sticky = tk.W+tk.E, pady=(0,10))
# Label and entry for degree.
label_d = tk.Label(text="Degree ->", bg = "#F5F5F5")
label_d.grid(row=1, column=0, columnspan=2, sticky = tk.W, padx=(10,0))
entry_d = tk.Entry(root, width=10, bg = "#e8e8e8")
entry_d.grid(row=1, column=2, columnspan=2, sticky = tk.E, padx=(0,10))
# Label and entry for minute.
label_m = tk.Label(text="Minute ->", bg = "#F5F5F5")
label_m.grid(row=2, column=0, columnspan=2, sticky = tk.W, padx=(10,0))
entry_m = tk.Entry(root, width=10, bg = "#e8e8e8")
entry_m.grid(row=2, column=2, columnspan=2, sticky = tk.E, padx=(0,10))
# Label and entry for second.
label_s = tk.Label(text="Second ->", bg = "#F5F5F5")
label_s.grid(row=3, column=0, columnspan=2, sticky = tk.W, padx=(10,0))
entry_s = tk.Entry(root, width=10, bg = "#e8e8e8")
entry_s.grid(row=3, column=2, columnspan=2, sticky = tk.E, padx=(0,10))
# Radiobutton for quadrant selection.
def retrieve():
print(quadrant_var.get())
quadrant_var = tk.StringVar(value = "N")
quad_button_n = tk.Radiobutton(root, text = "N", variable = quadrant_var, value = "N", command = retrieve, pady = 3)
quad_button_n.grid(row=4, column=0)
quad_button_e = tk.Radiobutton(root, text = "E", variable = quadrant_var, value = "E", command = retrieve, pady = 3)
quad_button_e.grid(row=4, column=1)
quad_button_s = tk.Radiobutton(root, text = "S", variable = quadrant_var, value = "S", command = retrieve, pady = 3)
quad_button_s.grid(row=4, column=2)
quad_button_w = tk.Radiobutton(root, text = "W", variable = quadrant_var, value = "W", command = retrieve, pady = 3)
quad_button_w.grid(row=4, column=3)
# Set blank variable for wait_variable
var = tk.IntVar()
# Button for calculating the conversion with wait_variable
calculate = tk.Button(text="Calculate", command=lambda: var.set(1))
calculate.grid(row=5, column=0, columnspan=2, sticky = tk.E+tk.W, padx=10, pady=10)
# Button to reset and allow for another calculation
calculate = tk.Button(text="Reset")
calculate.grid(row=5, column=2, columnspan=2, sticky = tk.E+tk.W, padx=10, pady=10)
# Label with placeohlder output text
label_output = tk.Label(text=" ", borderwidth=2, relief="groove", font="Arial, 12", pady=8)
label_output.grid(row=7, column=0, columnspan=4, sticky = tk.W+tk.E, padx=10)
# Label at the bottom of the application
label_foot = tk.Label(text="Developed by Ryan Seabrook", bg = "#F5F5F5", fg = "#7a7a7a", pady = 1)
label_foot.grid(row=8, column=0, columnspan=4, sticky = tk.W+tk.E)
# Wait for the user to press the calculate button.
calculate.wait_variable(var)
# Information from user input for degree minute second, converted to float for math calculation.
degree = float(entry_d.get())
minute = float(entry_m.get())
second = float(entry_s.get())
# Raw calculated output for DMS to DD.
calculated_dd = (float(degree) + (float(minute)/60) + (float(second)/3600))
# Rounded DD output.
rounded_dd = round(calculated_dd,8)
# Fetch string for final output
rounded_dd_str = str(rounded_dd)
final_output = "output"
selected_quadrant = quadrant_var.get()
# If statement to assign correct quadrant value to output
if selected_quadrant == "W":
final_output = "-" + rounded_dd_str + " " + selected_quadrant
elif selected_quadrant == "S":
final_output = "-" + rounded_dd_str + " " + selected_quadrant
else:
final_output = rounded_dd_str + " " + selected_quadrant
# Label for final output
label_output = tk.Label(text=final_output, borderwidth=2, relief="sunken", font="Arial 12", pady=8)
label_output.grid(row=7, column=0, columnspan=4, sticky = tk.W+tk.E, padx=10)
# Holds python while tkinter root window is open.
root.mainloop()
There seems to be a related post here,
Restart program tkinter
which also links to this code snippet on this page,
https://www.daniweb.com/programming/software-development/code/260268/restart-your-python-program
which may solve your problem.
I hope this helps!
Related
In my code, I have tried to get the user input through text fields, store them in variables and finally print them in a tabular form.
The problem I am facing is that none of the values I enter through the text fields get displayed; when I try printing the variables, they come up empty.
Here's part of my code:
# SPASC
from tkinter import *
import tkinter as tk
import tkinter.ttk as tktrv
root = tk.Tk()
root.title("SPASC")
root.geometry("410x400")
lb1 = Label(root, text="SPASC \n Welcomes You !!!", fg="red", bg="sky blue"
, font=('Arial Black', 20), width=22, anchor=CENTER)
lb2 = Label(root, text="What would you like to compare?",
font=('Arial', 18), anchor=CENTER)
space1 = Label(root, text="\n\n")
lb1.grid(row=0)
lb2.grid(row=5)
space1.grid(row=1)
hpw, mil = StringVar(), StringVar()
def bt_cars():
w1 = Toplevel()
w1.title("Choose Features")
w1.geometry("430x200")
lb3 = Label(w1, text="Choose features for comparison", bg="yellow"
, font=('Arial Black', 18), width=25)
lb4 = Label(w1, text=" ", anchor=CENTER)
fr1 = LabelFrame(w1, width=20, padx=100)
hpw_cb = Checkbutton(fr1, text="Horsepower", variable=hpw, anchor='w', onvalue="Horsepower", offvalue="")
hpw_cb.grid()
hpw_cb.deselect()
mil_cb = Checkbutton(fr1, text="Mileage", variable=mil, anchor='w', onvalue="Mileage", offvalue="")
mil_cb.grid()
mil_cb.deselect()
var_stor = [hpw, mil]
print(hpw)
print(mil)
var_fill = []
for itr1 in var_stor:
if itr1 != "":
var_fill.append(itr1)
print(var_fill)
def car_1():
name1 = StringVar()
c1 = Toplevel()
c1.title("Car 1")
c1.geometry("430x200")
car1_lb1 = Label(c1, text="Car Name:")
name1_ifl = Entry(c1)
name1 = name1_ifl.get()
elm_var_fill = len(var_fill)
ct1 = 0
car1_val = []
for itr2 in var_fill:
if ct1 == elm_var_fill:
break
lb5 = Label(c1, text=itr2.get())
#Creating text field
ftr1_ifl = Entry(c1)
car1_ftr = ftr1_ifl.get()
car1_val.append(car1_ftr)
car1_ftr = None
lb5.grid(row=ct1 + 2, column=1)
ftr1_ifl.grid(row=ct1 + 2, column=2)
ct1 += 1
print(car1_val)
def display():
dp = Toplevel()
dp.title("Results")
dp.geometry("500x200")
car1_pt = 0
car2_pt = 0
car_tree = tktrv.Treeview(dp)
car_tree["columns"] = ("car1col")
car_tree.column("#0", width=120, minwidth=30)
car_tree.column("car1col", width=120, minwidth=30)
car_tree.heading("#0", text="Features" )
car_tree.heading("car1col", text=str(name1))
car_tree.pack()
c1.withdraw()
print(var_fill)
done1_bt = Button(c1, text="Continue", command=display)
name1_ifl.grid(row=0, column=2)
car1_lb1.grid(row=0, column=1)
done1_bt.grid(row=5,column=1)
w1.withdraw()
done_bt = Button(w1, text="Done", command=car_1)
done_bt.grid(row=3, column=1)
lb3.grid(row=0, column=1)
lb4.grid(row=1, column=1)
fr1.grid(row=2, column=1)
root.withdraw()
bt1 = Button(root, text="CARS", width=5, font=('Calibri', 15), command=bt_cars)
bt1.grid(row=7)
space2 = Label(root, text="\n\n")
space2.grid(row=6)
root.mainloop()
I am facing trouble with the variables named: hpw, mil, name1.
Any help would be welcome.
NOTE:- Please excuse the amount of code; I wanted others to replicate the error and see it for themselves
For the variables hpw and mil, these variables are empty strings that's why you are not getting any value from those checkboxes. To get values from the checkboxes replace these lines of code:
var_stor = [hpw, mil]
with
var_stor = [hpw_cb.cget('onvalue'), mil_cb.cget('onvalue')]
since you want the onvalue then you must use cget() method to access those values.
also, replace
lb5 = Label(c1, text=itr2.get())
with
lb5 = Label(c1, text=itr2)
because now you have required values (not objects) in a list, so just need to access those values.
For the variable name1 you can use #BokiX's method.
The problem is you are using get() wrong. You cannot use get() right after Entry() because as soon as entry is created it's getting the input before the user can even input something.
Use this code:
def get_input(text):
print(text)
e = Entry(root)
e.pack()
b = Button(root, text="Print input", command=lambda: get_input(e.get()))
b.pack()
Now get() method will not be executed before you click the button.
I'm gonna preface this by saying that im quite new to this, dont judge haha.
The script im writing is to make a random password from different strings and randomize them. That I have already succeeded in completing, but know that I want to build a GUI for that script, the implementation with functions and tkinter is giving me trouble. I have two functions: One (add2all)that is supposed to check wether a variable is true, and if it is true add it to the string "all", that im later going to randomize with my second function. Im sure there are problems with how I get the value from the Checkbuttons (used to get the user input what kind of characters they want in the password), and then how they are added to the string. My second function (pwdgen) is supposed to get the input length from an Entry box were the user types an int, and then calls the add2all function to see what characters the user wants. add2all should generate a string with all the charracters that have been defined as true, so that pwdgen can randomize them with the given length. I also have a Button that is supposed to start the process. It calls on pwdgen, which then ccalls add2all and at the end, the variable password should have a randomized string which I can display to an entry box.
TL;DR: The function and tkinter implementation of a very simple script I previously wrote isn't working at all.
import random
from tkinter import *
from tkinter import ttk
root = Tk()
upper, lower, nums, syms = False, False, False, False
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercase = "abcdefghijklmnopqrstuvwxyz"
digits = "1234567890"
symbols = "!§$%&?*+#~-;()/"
all = StringVar()
CheckBool1 = IntVar()
CheckBool2 = IntVar()
CheckBool3 = IntVar()
CheckBool4 = IntVar()
pwlength = IntVar()
#function that checks if a CheckButton input (which characters are wanted in password)
#is true, if true adds the corresponding character string to the all string
def add2all():
if CheckBool1:
upper = True
if CheckBool2:
lower = True
if CheckBool3:
nums = True
if CheckBool4:
syms = True
if upper:
all += uppercase
if lower:
all += lowercase
if nums:
all += digits
if syms:
all += symbols
#function that gets password length from user, then calls add2all, then gives var password
#the string of all randomized with specified length and then puts it into entry box pwdoupt
def pwdgen():
pwdoutpt.delete(0, END)
v = amt.get()
v = pwlength
add2all()
password = "".join(random.choices(all, k=pwlength))
pwdoutpt.insert(0, password)
greet = Label(root, text="Welcome to the interactive password generator!", height=3)
pwdoutpt = Entry(root, width=30)
generate = Button(root, text="Generate", command = lambda: pwdgen())
#inits all the labels and checkbuttons for my gui
chck_1 = Checkbutton(root, width = 5, var = CheckBool1)
chck_2 = Checkbutton(root, width = 5, var = CheckBool2)
chck_3 = Checkbutton(root, width = 5, var = CheckBool3)
chck_4 = Checkbutton(root, width = 5, var = CheckBool4)
lbl_1 = Label(root, text="Capital Letters")
lbl_2 = Label(root, text="Lowercase Letters")
lbl_3 = Label(root, text="Digits")
lbl_4 = Label(root, text="Symbols")
amt = Entry(root, width = 5)
amtlbl = Label(root, text="Num of characters in pwd.")
sep = ttk.Separator(root, orient="horizontal")
greet.grid(column=0, row=0, columnspan=4, pady=3)
pwdoutpt.grid(column=0, row=7, columnspan=4, padx=30, sticky=W)
amt.grid(column=0, row=1, sticky=W)
amtlbl.grid(column=1, row=1, columnspan=1, sticky=E)
chck_1.grid(column=0, row=2, sticky=E)
chck_2.grid(column=0, row=3, sticky=E)
chck_3.grid(column=0, row=4, sticky=E)
chck_4.grid(column=0, row=5, sticky=E)
lbl_1.grid(column=1, row=2, columnspan=1, sticky=W)
lbl_2.grid(column=1, row=3, columnspan=1, sticky=W)
lbl_3.grid(column=1, row=4, columnspan=1, sticky=W)
lbl_4.grid(column=1, row=5, columnspan=1, sticky=W)
sep.grid(column=0, columnspan=10, row=6, sticky=EW)
generate.grid(column=2, row=7)
root.mainloop()
Firstly, don't use all as the variable name for your StringVar; it's a built-in python function. Don't use wildcard imports (from <module> import *), it's a bad habit and doesn't conform to PEP8. Instead, use import tkinter as tk.
You need to read how to use a StringVar; it is NOT a string and you can't add to it like one. A good application of using a StringVar in this code would be to display the generated password. If you bind the StringVar to your pwdoutpt Entry, updating the StringVar will automatically display the updated string.
You say you already had your password generator working correctly. Why not slightly adapt your password generator function so it takes the length and character types as inputs, and returns a randomly generated password? You are currently trying to integrate the password generating function into the GUI code, which is a bad idea is it can get messy super fast.
Taking all of the above into consideration, here is a working modified version of your code:
import random
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
# Your password generating function
def pwdgen(password_length, chars_allowed):
chars = [
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"1234567890",
"!§$%&?*+#~-;()/"
]
valid_chars = [x for i, x in enumerate(chars) if chars_allowed[i] == True]
valid_chars = "".join(valid_chars)
password = "".join(random.choices(valid_chars, k=password_length))
return password
# Set up tkinter window
root = tk.Tk()
root.title("Password generator")
# Vars for checkbuttons and password entry
CheckBool1 = tk.IntVar()
CheckBool2 = tk.IntVar()
CheckBool3 = tk.IntVar()
CheckBool4 = tk.IntVar()
password = tk.StringVar()
# Main widgets
greet = tk.Label(root, text="Welcome to the interactive password generator!", height=3)
chck_1 = tk.Checkbutton(root, width = 5, var = CheckBool1)
chck_2 = tk.Checkbutton(root, width = 5, var = CheckBool2)
chck_3 = tk.Checkbutton(root, width = 5, var = CheckBool3)
chck_4 = tk.Checkbutton(root, width = 5, var = CheckBool4)
lbl_1 = tk.Label(root, text="Capital Letters")
lbl_2 = tk.Label(root, text="Lowercase Letters")
lbl_3 = tk.Label(root, text="Digits")
lbl_4 = tk.Label(root, text="Symbols")
amt = tk.Entry(root, width = 5)
amtlbl = tk.Label(root, text="Num of characters in pwd.")
sep = ttk.Separator(root, orient="horizontal")
# Password output
pwdoutpt = tk.Entry(root, width=30, textvariable=password, state="readonly")
# Generate password function and button
def insert_password():
try:
password_length = int(amt.get())
chars_allowed = [CheckBool1.get(), CheckBool2.get(), CheckBool3.get(), CheckBool4.get()]
password.set(pwdgen(password_length, chars_allowed))
except ValueError:
messagebox.showerror("Error", "Invalid password length")
except IndexError:
messagebox.showerror("Error", "No character type selected")
generate = tk.Button(root, text="Generate", command = insert_password)
# Gridding widgets
greet.grid(column=0, row=0, columnspan=4, pady=3)
pwdoutpt.grid(column=0, row=7, columnspan=4, padx=30, sticky=tk.W)
amt.grid(column=0, row=1, sticky=tk.W)
amtlbl.grid(column=1, row=1, columnspan=1, sticky=tk.E)
chck_1.grid(column=0, row=2, sticky=tk.E)
chck_2.grid(column=0, row=3, sticky=tk.E)
chck_3.grid(column=0, row=4, sticky=tk.E)
chck_4.grid(column=0, row=5, sticky=tk.E)
lbl_1.grid(column=1, row=2, columnspan=1, sticky=tk.W)
lbl_2.grid(column=1, row=3, columnspan=1, sticky=tk.W)
lbl_3.grid(column=1, row=4, columnspan=1, sticky=tk.W)
lbl_4.grid(column=1, row=5, columnspan=1, sticky=tk.W)
sep.grid(column=0, columnspan=10, row=6, sticky=tk.EW)
generate.grid(column=2, row=7)
root.mainloop()
Some further notes on the code for you:
The function insert_password uses a try except to test if the inputs are correct before generating the password.
pwdoutpt has state="readonly" so that the user can't modify the generated password but can still copy it
I have a python GUI assignment in which I have to create a GUI application which will evaluate a single variable function within a specified range of input values. We have to use classes. I have written the following code:
from tkinter import *
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
import tkinter.font as font
class eval_interface:
def __init__(self):
self.root = Tk()
self.root.title("Function Evaluator")
self.topframe = Frame(self.root)
self.createTopFrame()
self.topframe.grid(row=0, column=0, columnspan=10, sticky=N + S + W + E)
self.frame2 = Frame(self.root)
self.createFrame2()
self.frame2.grid(row = 1, column = 0, pady = 15, columnspan = 10, sticky = N + S + W + E)
self.frame3 = Frame(self.root)
self.createFrame3()
self.frame3.grid(row=2, column=0, pady=15, columnspan=10, sticky=N + S + W + E)
self.frame4 = Frame(self.root)
self.frame5 = Frame(self.root)
self.createFrame5()
self.frame5.grid(row=4, column=0, pady=15, columnspan=10, sticky=N + S + E + W)
self.createFrame4()
self.frame4.grid(row = 3, column = 0, pady = 15, columnspan = 10, sticky = N+S+E+W)
self.root.mainloop()
def createTopFrame(self): #Frame containing title
title = Label(self.topframe, text="Function evaluator and plotter".center(228, " "), font=font.Font(size=17))
title.grid(row=0, column=0, columnspan=7)
def createFrame2(self): #Frame containing function Entry widget
title = Label(self.frame2, text = "Enter the function in x : ", font = font.Font(size = 14))
title.grid(row = 0, column = 0, sticky = N + S + W + E)
function_entry = Entry(self.frame2, width = 150)
function_entry.grid(row = 0, column = 1, sticky = N + S + W + E)
def createFrame3(self): #Frame containing range Entry widgets
range_label = Label(self.frame3, text="Enter the range of the function from : ", font = font.Font(size = 14))
lower_range_entry = Entry(self.frame3, width=10)
range_label2 = Label(self.frame3, text=" to ")
upper_range_entry = Entry(self.frame3, width=10)
range_label.grid(row=1, column=0, sticky="nsew")
lower_range_entry.grid(row=1, column=1)
range_label2.grid(row=1, column=2, sticky="nsew")
upper_range_entry.grid(row=1, column=3, sticky="nsew")
def createFrame4(self): #Frame containing button widgets
btn_evaluate = Button(self.frame4, text = "Evaluate", font = font.Font(size = 14), command = self.evaluate())
btn_plot = Button(self.frame4, text = "Plot", font = font.Font(size = 14))
btn_clear = Button(self.frame4, text = "Clear", font = font.Font(size = 14))
btn_exit = Button(self.frame4, text = "Exit", font = font.Font(size = 14), command = exit)
btn_evaluate.grid(row=0, column=0, padx=10, pady=5)
btn_plot.grid(row=0, column=1, padx=10, pady=5)
btn_clear.grid(row=0, column=2, padx=10, pady=5)
btn_exit.grid(row=0, column=3, padx=10, pady=5)
def createFrame5(self): #Frame containing Result Textbox
res_text = Text(self.frame5, width = 95, height = 55, padx = 10)
res_text.grid(row = 0, column = 0)
def evaluate(self):
x = 10
def clear(self):
z=12
eval_interface()
My question is, how do I access the data inputted by the user in the three entry widgets (in frames 2 and 3) when the Evaluate button is clicked? And after I have accessed the data and done the necessary operations on it, how do I display the result in the Textbox in Frame 5? (I have just coded some random statement in evaluate and clear functions for now to see the output GUI.)
If you want to access the Entry widgets inside evaluate() function, you need to change the three local variables function_entry, lower_range_entry and upper_range_entry to instance variables self.function_entry, self.lower_range_entry and self.upper_range_entry. Same for the Text widget res_text. Then you can get the values from the three Entry widgets and insert the result into self.res_text inside evaluate() function:
def createFrame2(self): #Frame containing function Entry widget
title = Label(self.frame2, text = "Enter the function in x : ", font = font.Font(size = 14))
title.grid(row = 0, column = 0, sticky = N + S + W + E)
self.function_entry = Entry(self.frame2, width = 150)
self.function_entry.grid(row = 0, column = 1, sticky = N + S + W + E)
def createFrame3(self): #Frame containing range Entry widgets
range_label = Label(self.frame3, text="Enter the range of the function from : ", font = font.Font(size = 14))
self.lower_range_entry = Entry(self.frame3, width=10)
range_label2 = Label(self.frame3, text=" to ")
self.upper_range_entry = Entry(self.frame3, width=10)
range_label.grid(row=1, column=0, sticky="nsew")
self.lower_range_entry.grid(row=1, column=1)
range_label2.grid(row=1, column=2, sticky="nsew")
self.upper_range_entry.grid(row=1, column=3, sticky="nsew")
...
def createFrame5(self): #Frame containing Result Textbox
self.res_text = Text(self.frame5, width = 95, height = 55, padx = 10)
self.res_text.grid(row = 0, column = 0)
def evaluate(self):
# get content from entries
x = self.function_entry.get()
lower = self.lower_range_entry.get()
upper = self.upper_range_entry.get()
# example on inserting result into text box
result = ", ".join([x, lower, upper]) # or whatever you want
self.res_text.insert("end", result)
...
Also command=self.evaluate() inside createFrame4() should be command=self.evaluate instead.
I'm pretty new with tkinter and I can't figure why the q is not aligned near the Entry.
# String
self.user_p = StringVar()
self.user_q = StringVar()
self.user_r = StringVar()
self.user_result = StringVar()
# Label
self.description = Label(self.root, text="!p v (q ^ r)")
self.pLabel = Label(self.root, text="p")
self.qLabel = Label(self.root, text="q")
self.rLabel = Label(self.root, text="r")
self.resultLabel = Label(self.root, text="Result")
# Entry
self.p = Entry(self.root, textvariable = self.user_p, width = 10)
self.q = Entry(self.root, textvariable = self.user_q, width = 10)
self.r = Entry(self.root, textvariable = self.user_r, width = 10)
self.result = Entry(self.root, bg = "white", state=DISABLED, text = "")
# Grid
# Labels
self.description.grid(row = 0, column = 3, sticky = N)
self.pLabel.grid(row = 1, column = 0, sticky = E)
self.qLabel.grid(row = 1, column = 2, sticky = E)
self.rLabel.grid(row = 1, column = 4, sticky = E)
# Entry
self.p.grid(row=1, column=1)
self.q.grid(row = 1, column = 3)
self.r.grid(row=1, column=5)
(with or without the sticky it's still the same)
Here's a picture: http://imgur.com/a/wrOGa
The first part in the picture is what I'm getting right now. And the second part is what I want it to look like
Am I doing something wrong?
Welcome. I have taken the liberty to attach an example of a test code (see below). Please remember to do that in your post as mine can be different to yours. I did not encounter the issue you described. See attached picture. I am using python3.5 on Ubuntu 16.04.
One other thing, you can be more explicit by adding the option justify=RIGHT in your label widget commands to alight the label text to right.
from tkinter import *
class App(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background='pink')
# String
self.user_p = StringVar()
self.user_q = StringVar()
self.user_r = StringVar()
self.user_result = StringVar()
# Label
self.description = Label(self, text="!p v (q ^ r)")
self.pLabel = Label(self, text="p")
self.qLabel = Label(self, text="q")
self.rLabel = Label(self, text="r")
self.resultLabel = Label(self, text="Result")
# Entry
self.p=Entry(self, textvariable=self.user_p, width=10)
self.q=Entry(self, textvariable=self.user_q, width=10)
self.r=Entry(self, textvariable=self.user_r, width=10)
self.result=Entry(self, bg="white", state=DISABLED, text="")
# Grid
# Labels
self.description.grid(row=0, column=3, sticky=N)
self.pLabel.grid(row=1, column=0, sticky=E)
self.qLabel.grid(row=1, column=2, sticky=E)
self.rLabel.grid(row=1, column=4, sticky=E)
# Entry
self.p.grid(row=1, column=1)
self.q.grid(row=1, column=3)
self.r.grid(row=1, column=5)
if __name__ == '__main__':
root=Tk()
root.geometry("300x50")
app=App(root)
app.pack(fill="both", expand=True)
app.mainloop()
I would like to create 2 different groups of radio buttons. The user would select one option from either group. There would be a function that would get the values(strings) from the selected radio buttons and then print them. Here's my code but it doesn't work (i'm new to python).
from tkinter import *
root = Tk()
btn1 = "lol"
btn2 = "lel"
def funkcija():
n = entry1.get()
m = "null"
X = btn1.get()
Y = btn2.get()
print("%s %s je %s %s." % (n, X, m, Y))
theLabel = Label(root, text="Vnesite količino in izberite prvo valuto.")
theLabel.grid(row=0, columnspan=3)
gumb1=Radiobutton(root,text="Euro",value = "euro",variable = "btn1").grid(row=2, column=1, sticky=W)
gumb2=Radiobutton(root,text="Dolar",value = "dolar",variable = "btn1").grid(row=3, column=1, sticky=W)
gumb3=Radiobutton(root,text="Funt",value = "funt",variable = "btn1").grid(row=4, column=1, sticky=W)
label3= Label(root, text="Izberite drugo valuto.")
label3.grid(row=6, columnspan=3)
label35= Label(root)
label35.grid(row=5, columnspan=3)
gumb4=Radiobutton(root,text="Euro",value = "euro",variable = "btn2").grid(row=7, column=1, sticky=W)
gumb5=Radiobutton(root,text="Dolar",value = "dolar",variable = "btn2").grid(row=8, column=1, sticky=W)
gumb6=Radiobutton(root,text="Funt",value = "funt",variable = "btn2").grid(row=9, column=1, sticky=W)
label1 = Label(root, text="Količina:")
label1.grid(row=1, sticky=E)
entry1 = Entry(root)
entry1.grid(row=1, column=1, sticky=W)
go = Button(root, text="Izračun", fg="white", bg="black", command=funkcija)
go.grid(row=10, columnspan=3)
root.mainloop()
In your radio button, analyze the parameters that you are passing:
gumb1 = Radiobutton(root,
text = "Euro",
value = "Euro",
variable = "btn2"
The parameters value and variable are what stores the data of the radio button. You've set your value option correctly. The interpreter will automatically set the variable with the value when the radio button is selected.
But here's where your issue is:
variable = "btn2"
"btn2" is a string. Not very useful though, is it? In fact, you're trying to perform methods on it that don't even exist. Such as here:
def funkcija():
X = btn2.get()
In fact, taking this information, you almost got there!
At the top of your script, you need to set btn2 to Tkinter's StringVar, like so:
from tkinter import *
btn1 = StringVar()
btn2 = StringVar()
Now that's done, let's change our parameters in our radio buttons.
gumb1 = Radiobutton(root,
text = "Euro",
value = "Euro",
variable = btn2
Now, Tkinter will automatically update the variable when it is selected. To get the value, do the same that you had done in your funkcija.
X = btn2.get()
And then the value of btn2 (which was updated by the radio buttons) will not be read, and stored into the variable X.