I have an issue where all my radio buttons are selected when I try to click one of them. It is for a conversion calculator, so once I solve this issue I will be able to carry the same code over for my other conversions. Any help is greatly appreciated.
Thanks,
Jamie
`from tkinter import*
from tkinter import ttk
class GUI:
def __init__(self, root):
notebook = ttk.Notebook(root)
notebook.pack()
self.temp_frame = ttk.Frame(notebook)
self.length_frame = ttk.Frame(notebook)
self.weight_frame = ttk.Frame(notebook)
#-----------------Length------------------------#
notebook.add(self.length_frame, text = "Length")
#Radio Buttons
v = StringVar()
MODES = ["mm","cm","Inch","Feet","Yards","Metre","Km","Miles"]
v.set("0") # initialize
r=0
for r in range(len(MODES)):
b = ttk.Radiobutton(self.length_frame, text=MODES[r], variable=v )
b.grid(row=r ,column = 0, sticky = W)
#Radio Buttons
v1 = StringVar()
MODES1 = ["mm","cm","Inch","Feet","Yards","Metre","Km","Miles"]
v1.set("0")#initialize
r=0
for r in range(len(MODES1)):
b = ttk.Radiobutton(self.length_frame, text=MODES1[r], variable=v1 )
b.grid(row=r ,column = 6, sticky = W)
#Entry Box
self.Text_length_left = StringVar()
self.entry_length_left = ttk.Entry(self.length_frame, textvariable = self.Text_length_left, width = 15)
self.entry_length_left.grid(row = 4, column = 2)
self.Text_length_right = StringVar()
self.entry_length_right = ttk.Entry(self.length_frame, textvariable = self.Text_length_right, width = 15, state = "readonly")
self.entry_length_right.grid(row = 4, column = 4)
#Label
self.label_3 = Label(self.length_frame, text = "From:")
self.label_3.grid(row = 3, column = 2)
self.label_4 = Label(self.length_frame, text = "To:")
self.label_4.grid(row = 3, column = 4)
self.label_1 = Label(self.length_frame, text = "-->")
self.label_1.grid(row = 4, column = 3)
self.label_2 = Label(self.length_frame, text = " ")
self.label_2.grid(row = 4, column = 5)
#---------------------Temp Frame ----------------------#
notebook.add(self.temp_frame, text = "Temperature")
if __name__ == "__main__":
root = Tk()
app = GUI(root)
root.mainloop()`
You never set the value keyword. This is what's stored in the control variable for a group of radiobuttons when clicked.
Related
I am creating a currency converter that asks the user to choose the starting and ending currencies with two optionmenu widgets. The problem I have run into is after the currency has been converted, I want to create a button that reverses the optionmenu values to convert back to the original currency. For example, I originally convert 20 USD to EUR. I want the button to reverse it to convert 20 EUR to USD and reflect the change in the optionmenus. Here is the code I have:
currency_list = []
infile = open('currency_list.txt', 'r')
for currency in infile:
currency_list[:-1]
currency_list.append(currency.strip("\t\n\t"))
initial1 = currency_list[-16] # initially set first option menu to USD from currency list
initial2 = currency_list[43] # initially set second option menu to EUR from currency list
my_list = [currency_list[-16], currency_list[43]]
class CurrencyConverter(tk.Frame):
def reverse(self):
my_list.reverse()
print (my_list)
self.currency_1_menu = tk.OptionMenu(self, self.currency_1, *currency_list)
self.currency_2_menu = tk.OptionMenu(self, self.currency_2, *currency_list)
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
body_color = "white"
body_font_color = "black"
entry_color = body_color
entry_font_color = "gray26"
self.currency_1 = tk.StringVar() # currency to convert from
self.currency_2 = tk.StringVar() # currency to convert to
self.currency_1.set(my_list[0]) # set value from list above
self.currency_2.set(my_list[1]) # set value from list above
self.answer = tk.StringVar() # result from conversion
self.value_id = tk.StringVar() # number user types in to convert from
self.header_text = tk.StringVar() # header to display information
logo = tkinter.PhotoImage(file = "logo_copy.gif") # import logo. Not working!!
label = tk.Label(self,image = logo)
label.config(bg = body_color)
label.grid(row = 0, column = 2, rowspan = 2)
self.header = tk.Label(self, textvariable = self.header_text)
self.result_label = tk.Label(self, textvariable = self.answer, fg = body_font_color)
self.value_entry = tk.Entry(self, textvariable = self.value_id)
self.currency_1_menu = tk.OptionMenu(self, self.currency_1, *currency_list)
self.currency_2_menu = tk.OptionMenu(self, self.currency_2, *currency_list)
self.calculate_button = tk.Button(self, command = self.convert, text = 'calculate')
self.reverse_button = tk.Button(self, command = lambda: self.reverse, text = 'reverse')
home_page_button = tk.Button(self, text = "Home Page", command = lambda: controller.show_frame(StartPage))
self.header.config(bg = body_color, font = ('arial', 12), fg = entry_font_color)
self.result_label.config(font = ('Arial', 36))
self.value_entry.config(font = 'bold', justify = 'center', bg = entry_color, fg = entry_font_color, highlightthickness = 0)
self.currency_1_menu.config(bg = body_color, width = 25, height = 2)
self.currency_2_menu.config (bg = body_color, width = 25, height = 2)
self.result_label.config (bg = body_color)
self.calculate_button.config (bg = body_color, highlightbackground = body_color)
self.reverse_button.config (bg = body_color, highlightbackground = body_color)
self.header.grid(row = 0, column = 0, sticky = 'w')
self.result_label.grid(row = 1, column = 0, sticky = 'w')
self.value_entry.grid(row = 2, column = 0)
self.currency_1_menu.grid (row = 2, column = 1)
self.currency_2_menu.grid (row = 3, column = 1)
self.calculate_button.grid(row = 4, column = 0)
self.reverse_button.grid(row = 2, column = 2, rowspan = 2)
home_page_button.grid(row = 4, column = 1)
def convert(self):
self.currency_1_iso = self.currency_1.get()[0:3]
self.currency_2_iso = self.currency_2.get()[0:3]
url = "https://www.xe.com/currencyconverter/convert/?Amount=" + self.value_id.get() + "&From=" + self.currency_1_iso + "&To=" + self.currency_2_iso
print(url)
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and
getattr(ssl, '_create_unverified_context', None)):
ssl._create_default_https_context = ssl._create_unverified_context
html_code = urllib.request.urlopen(url).read()
self.soup = BeautifulSoup(html_code, 'html.parser')
self.result = self.soup.find('span', {'class': "uccResultAmount"}).string
self.answer.set(self.result + " " + self.currency_2_iso)
self.header_text.set(self.value_id.get() + self.currency_1.get()[5:] + ' equals')
Your current attempt at reverse() creates brand new OptionMenus - and never actually displays them. You don't actually need to touch the OptionMenus themselves, just swap the values in the two variables they are tied to:
temp = self.currency_1.get()
self.currency_1.set(self.currency_2.get())
self.currency_2.set(temp)
Hello Python community,
Im using Python 3.6 and Im stumped on how to display a stored item in an empty list to a list box. Can anyone evaluate my code and tell me what I'm missing? Thanks in advance!
from tkinter import *
root = Tk()
root.title("Name Entry")
root.geometry("240x250")
mylist = []
def get_data(l):
l.append(box1.get())
print(l)
label1 = Label(root,text = "ID:",height = 2)
label1.grid(row = 0, column = 0)
ID=StringVar()
box1 = Entry(root, bd = 4, textvariable = ID)
box1.grid(row = 0, column = 1)
botonA = Button(root, text = "accept",command=lambda: get_data(mylist), width = 5)
botonA.grid(row = 0, column = 2)
list_names = Listbox(root).grid(row = 2, column = 1, rowspan = 7)
for item in mylist:
list_names.insert("end", item)
root.mainloop()
With the help from Matteo, I was able to creat what I wanted. Thanks again for clearing this up for me! :)
{from tkinter import *
root = Tk()
root.title("Name Entry")
root.geometry("240x250")
mylist = []
def get_data(l):
l.append(box1.get())
print(l)
display_data()
def display_data():
list_names.delete(0, "end")
for items in mylist:
list_names.insert(END, items)
label1 = Label(root,text = "ID:",height = 2)
label1.grid(row = 0, column = 0)
ID = StringVar()
box1 = Entry(root, bd = 4, textvariable = ID)
box1.grid(row = 0, column = 1)
botonA = Button(root, text = "accept",command = lambda: get_data(mylist),
width = 5)
botonA.grid(row = 0, column = 2)
list_names = Listbox(root)
list_names.grid(row = 2, column = 1, rowspan = 7)
root.mainloop()}
You have to insert the element when the button is pressed! In your code you are adding it to the listbox when mylist was empty.
Here is the working code:
from tkinter import *
root = Tk()
root.title("Name Entry")
root.geometry("240x250")
mylist = []
def get_data(l):
l.append(box1.get())
list_names.insert(END, l)
print(l)
label1 = Label(root, text="ID:", height=2)
label1.grid(row=0, column=0)
ID = StringVar()
box1 = Entry(root, bd=4, textvariable=ID)
box1.grid(row=0, column=1)
botonA = Button(root, text="accept", command=lambda: get_data(mylist), width=5)
botonA.grid(row=0, column=2)
list_names = Listbox(root)
list_names.grid(row=2, column=1, rowspan=7)
root.mainloop()
I also modified two other things:
I'm not sure if it's what you wanted but l.append(box1.get()) adds to the listbox all the element of the list, and not just the last one as I think you need.
list_names = Listbox(root).grid(row = 2, column = 1, rowspan = 7) means that the list_names variable is the result of the grid function (which is None). You have to first save the ListBox variable, and the grid it.
I'm new to Python and just started venturing into doing GUIs. I created a Tkinter window that is pretty basic: it has 3 Entry bars and 3 File Dialog buttons. When you chose the 3rd directory, the GUI file automatically makes a call to a separate file and receives a large text block which is then displayed in a Text box.
The whole thing works correctly, but my problem is that after receiving and inserting the text response, Tkinter stops working and doesn't allow the user to scroll down.
I read that one reason this happens is because people use both .pack( ) and .grid( ), but I'm not mixing those two functions.
Thanks in advance for any help!
Here's my GUI file
from tkinter import *
from tkinter import filedialog
from gui_GPSExtractor import *
import os
class Application(Frame):
def __init__(self, master):
""" Initialize Frame """
Frame.__init__(self, master)
self.grid( )
self.startGUI( )
""" Create Labels, Text Boxes, File Dialogs, and Buttons """
def startGUI(self):
# Label for Scan Path
self.dLabel = Label(self, text = "Scan Path")
self.dLabel.grid(row = 0, column = 0, columnspan = 2, sticky = W)
# Entry for Scan Path
self.dEntry = Entry(self, width = 60)
self.dEntry.grid(row = 1, column = 0, sticky = W)
# Button for Scan Path Directory Browse
self.dButton = Button(self, text = "Browse", command = lambda: self.browseFiles("d"))
self.dButton.grid(row = 1, column = 1, sticky = W)
# Label for CSV Path
self.cLabel = Label(self, text = "CSV Path")
self.cLabel.grid(row = 3, column = 0, columnspan = 2, sticky = W)
# Entry for CSV Path
self.cEntry = Entry(self, width = 60)
self.cEntry.grid(row = 4, column = 0, sticky = W)
# Button for CSV Path Directory Browse
self.cButton = Button(self, text = "Browse", command = lambda: self.browseFiles("c"))
self.cButton.grid(row = 4, column = 1, sticky = W)
# Label for Log Path
self.lLabel = Label(self, text = "Log Path")
self.lLabel.grid(row = 6, column = 0, columnspan = 2, sticky = W)
# Entry for Log Path
self.lEntry = Entry(self, width = 60)
self.lEntry.grid(row = 7, column = 0, sticky = W)
# Button for Log Path Directory Browse
self.lButton = Button(self, text = "Browse", command = lambda: self.browseFiles("l"))
self.lButton.grid(row = 7, column = 1, sticky = W)
# Text Box for Results
self.resultText = Text(self, width = 60, height = 30, wrap = WORD, borderwidth = 3, relief = SUNKEN)
self.resultText.grid(row = 9, column = 0, columnspan = 2, sticky = "nsew")
# Scrollbar for Text Box
self.scrollBar = Scrollbar(self, command = self.resultText.yview)
self.scrollBar.grid(row = 9, column = 2, sticky = "nsew")
self.resultText["yscrollcommand"] = self.scrollBar.set
def browseFiles(self, btnCalling):
if(btnCalling == "d"):
self.dName = filedialog.askdirectory(initialdir = "/python3-CH05")
self.dEntry.delete(0, END)
self.dEntry.insert(0, self.dName)
elif(btnCalling == "c"):
self.cName = filedialog.askdirectory(initialdir = "/python3-CH05")
self.cEntry.delete(0, END)
self.cEntry.insert(0, self.cName)
elif(btnCalling == "l"):
self.lName = filedialog.askdirectory(initialdir = "/python3-CH05")
self.lEntry.delete(0, END)
self.lEntry.insert(0, self.lName)
output = extractGPS(self.dName, self.cName, self.lName)
self.resultText.delete(0.0, END)
self.resultText.insert(0.0, output)
# Start the GUI
root = Tk( )
root.title("Python gpsExtractor")
root.geometry("650x650")
app = Application(root)
root.mainloop( )
I am trying to calculate a formula and display its output as a table in TKinter. Since it is not working, I am just trying to get a simple result and print it to a canvas widget. When this gets working I will do the entire loan formula. As it is I get no output in the GUI or in the console.
Is this even possible to place the result of a calculation as text in canvas.create_text?
from tkinter import * # Import tkinter
width = 500
height = 500
class MainGUI:
def __init__(self):
window = Tk() # Create a window
window.title(" Loan Schedule ") # Set title
frame1 = Frame(window)
frame1.grid(row = 1, column = 1)
Label(frame1, text = " Loan Amount ").grid(row = 1, column = 1, sticky = W)
self.v1 = StringVar()
Entry(frame1, textvariable = self.v1, justify = RIGHT).grid(row = 1, column = 2)
Label(frame1, text = " Years ").grid(row = 1, column = 3, sticky = W)
self.v2 = StringVar()
Entry(frame1, textvariable = self.v2, justify = RIGHT).grid(row = 1, column = 4)
btCalculate = Button(frame1, text = " Calculate ", command = self.calculate()).grid(row = 1, column = 5, sticky = E)
frame2 = Frame(window)
frame2.grid(row = 2, column = 1)
self.canvas = Canvas(frame2, width = width, height = height, bg = "white")
self.canvas.pack()
self.canvas.create_text(25, 25, text = self.calculate(), tags = "text")
window.mainloop() # Create an event loop
def calculate(self):
result = self.v1.get() + self.v2.get()
print(result)
return result
MainGUI()
command require function name without ()
command = self.calculate
so now it works
from tkinter import * # Import tkinter
width = 500
height = 500
class MainGUI:
def __init__(self):
window = Tk() # Create a window
window.title(" Loan Schedule ") # Set title
frame1 = Frame(window)
frame1.grid(row = 1, column = 1)
Label(frame1, text = " Loan Amount ").grid(row = 1, column = 1, sticky = W)
self.v1 = StringVar()
Entry(frame1, textvariable = self.v1, justify = RIGHT).grid(row = 1, column = 2)
Label(frame1, text = " Years ").grid(row = 1, column = 3, sticky = W)
self.v2 = StringVar()
Entry(frame1, textvariable = self.v2, justify = RIGHT).grid(row = 1, column = 4)
btCalculate = Button(frame1, text = " Calculate ", command = self.calculate).grid(row = 1, column = 5, sticky = E)
frame2 = Frame(window)
frame2.grid(row = 2, column = 1)
self.canvas = Canvas(frame2, width = width, height = height, bg = "white")
self.canvas.pack()
self.canvas.create_text(55, 10, text = self.add_text(), tags = "text")
window.mainloop() # Create an event loop
def calculate(self):
result = int(self.v1.get()) + int(self.v2.get())
self.canvas.create_text(25, 25, text = result, tags = "text")
print(result)
return result
def add_text(self):
return "HELLO WORLD"
MainGUI()
by the way: line below means - run self.calculate() and result assign to command
command = self.calculate()
I'd like to make a program which draws a cosinus graph in orderd range. But there is an error which I'm not able to repair. Error Message: "z = int(self.entry.get())
AttributeError: program instance has no attribute 'entry" Here is my code:
# -*- coding: utf-8 -*-
from Tkinter import Tk, W, E
from ttk import Label, Button, Frame, Entry,Style
import math
import sys
import matplotlib as mp
class program(Frame):
def __init__(self,main):
Frame.__init__(self,main)
self.main = main
self.initUI()
def initUI(self):
self.main.title('COSINUSEK')
Style().configure('TFrame', background = 'black')
Style().configure('TLabel', background = 'black', foreground = 'blue')
Style().configure("TButton", background = 'red', foreground = 'blue')
self.rowconfigure(0, pad = 3)
self.rowconfigure(1, pad = 3)
self.rowconfigure(2, pad = 3)
self.rowconfigure(3, pad = 3)
self.rowconfigure(4, pad = 3)
self.columnconfigure(0,pad =3)
self.columnconfigure(1,pad =3)
self.columnconfigure(2,pad =3)
self.columnconfigure(3,pad =3)
self.columnconfigure(4,pad =3)
label = Label(self, text = 'Podaj zakres w stopniach').grid(row = 0,column = 3)
od = Label(self, text = ' OD').grid(row = 1, column =0)
do = Label(self, text = ' DO').grid(row = 1, column =4 )
entry = Entry(self, justify = 'center').grid(row = 2,column = 0,columnspan = 2 ,sticky = E+ W)
entry1 = Entry(self, justify = 'center').grid(row = 2,column = 4,columnspan = 2, sticky = E)
button = Button(self, text = 'Ok',command = self.ok).grid(row = 3,column = 3)
button1 = Button(self, text = 'Draw', command = self.dra).grid(row = 4, column = 3)
self.pack()
def run(self):
self.main.mainloop()
def ok(self):
x = []
y = []
z = int(self.entry.get())
w = int(self.entry1.get())
i = w
while i in range(w,z):
x.append(i)
for a in x:
y[a] = math.cos((x[a]*math.pi)/180)
i = i + 0.01
def dra(self):
self.mp.ion()
self.mp.plot(self.x,self.y)
self.mp.title('Wykres')
self.mp.xlabel('x')
self.mp.ylabel('y')
self.mp.draw()
program(Tk()).run()
Replace:
entry = Entry(self, justify = 'center').grid(row = 2,column = 0,columnspan = 2 ,sticky = E+ W)
entry1 = Entry(self, justify = 'center').grid(row = 2,column = 4,columnspan = 2, sticky = E)
to
self.entry = Entry(self, justify = 'center')
self.entry.grid(row = 2,column = 0,columnspan = 2 ,sticky = E+ W)
self.entry1 = Entry(self, justify = 'center')
self.entry1.grid(row = 2,column = 4,columnspan = 2, sticky = E)
Otherwise, at line z = int(self.entry.get()), self.entry would not exist. Also, the grid method doesn't return anything so, if you do everything in one line as you did, you lose your Entry object and affect None to entry.
When making the variables, you'll have to set them as instance variables:
self.entry = Entry(self, justify = 'center').grid(row = 2,column = 0,columnspan = 2 ,sticky = E+ W)
self.entry1 = Entry(self, justify = 'center').grid(row = 2,column = 4,columnspan = 2, sticky = E)