I've made this converter. I want it to convert decimal values into binary and hexadecimal using Tkinter..
I made a text input box but I don't know how to get the input values from the input box.
We aren't supposed to use OOP so we can't use classes.
Here is my code (it's in french for some parts) :
import tkinter as tk
from tkinter import *
def ConverterWind():
convertisseur = Tk()
convertisseur.title("Convertisseur")
inputZone = Text(convertisseur, height=2, width=50)
inputZone.pack()
getTextArea = Button(convertisseur, text = "Convertir !", command = getText)
getTextArea.pack()
convertisseur.mainloop
MainMenu = Tk()
MainMenu.title("Choix de Modes")
button1 = Button(MainMenu, text = "convertisseur", command = ConverterWind)
button1.pack(side = LEFT, padx= 10, pady = 10)
button2 = Button(MainMenu, text = "QUITTER", command = MainMenu.destroy)
button2.pack(side = RIGHT, padx= 10, pady = 10)
MainMenu.mainloop()
You can use the Text.get(Index1,Index2) to get the text from Text widget
Try this.
import tkinter as tk
from tkinter import *
def getText(inputText):
print(inputText.get(1.0,END))
def ConverterWind():
convertisseur = Tk()
convertisseur.title("Convertisseur")
inputZone = Text(convertisseur, height=2, width=50)
inputZone.pack()
getTextArea = Button(convertisseur, text = "Convertir !", command = lambda: getText(inputZone))
getTextArea.pack()
convertisseur.mainloop
MainMenu = Tk()
MainMenu.title("Choix de Modes")
button1 = Button(MainMenu, text = "convertisseur", command = ConverterWind)
button1.pack(side = LEFT, padx= 10, pady = 10)
button2 = Button(MainMenu, text = "QUITTER", command = MainMenu.destroy)
button2.pack(side = RIGHT, padx= 10, pady = 10)
MainMenu.mainloop()
Related
Not really sure what im doing in this stage tbh, found someone asking a similar thing and tried to include it. However im not sure how to integrate it and at the moment they both do their own tkinter windows. One saving a .txt file, the other producing what ive written.
import sys
import tkinter as tk
from tkinter import *
from tkinter.messagebox import showinfo
root = tk.Tk()
root.wm_title('QR Code Generator')
def login():
frame = Frame(root)
Label(frame, text = "Welcome to QR Code Generator").grid(row = 0)
Label(frame, text = "Enter the link you want as a QR Code ").grid(row = 1)
e1 = Entry(frame)
e1.grid(row=1, column = 1)
Button(frame, text = 'Continue', command = save).grid(row = 4, column = 1, sticky = W, pady = 4)
return frame
def save():
file_name = entry.get()
with open(file_name + '.txt', 'w') as file_object:
file_object.write(file_name)
if __name__ == '__main__':
top = tk.Tk()
entry_field_variable = tk.StringVar()
entry = tk.Entry(top, textvariable=entry_field_variable)
entry.pack()
tk.Button(top, text="save", command=save).pack()
login_frame = login()
login_frame.pack(fill="both", expand=True)
root.mainloop()
wanting the "paste link for qr code" section to be saved into a .txt
Your filename is not defined anywhere in the code
I.e. your filename is empty, this results in a file with no name '.txt'
def save():
file_name = entry.get()
with open(file_name + '.txt', 'w') as file_object:
file_object.write(file_name)
Your code opens two windows, it is being created in this line, whenever you define another instance of Tk() it will be a new window, if you need it, I recommend Toplevel
if __name__ == '__main__':
top = tk.Tk()
Try something cleaner and easier to understand
import tkinter as tk
from tkinter import *
root = tk.Tk()
root.wm_title('QR Code Generator')
def save():
content = e1.get()
with open('your_file.txt', 'w') as file_object:
file_object.write(content)
frame = Frame(root)
frame.pack()
Label(frame, text="Welcome to QR Code Generator").pack()
Label(frame, text="Enter the link you want as a QR Code ").pack()
e1 = Entry(frame)
e1.pack()
Button(frame, text='Continue', command=save).pack()
if __name__ == '__main__':
root.mainloop()
The qrcode is created as a picture. You can write a picture as base64 encoded to a text file, but I recommend to save the picture as an image.
I understood your request as "create" and "show" the saved picture into a tkinter window. I saved the picture with a timestamp.
My prototype:
import tkinter as tk
import qrcode
from PIL import ImageTk, Image
import time
root = tk.Tk()
root.title('QR Code Generator')
root.geometry("450x420")
#root.state("zoomed") whole display size
root.config(bg="#2c3e50")
#root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
def create_QR(link_input):
print(link_input.get())
lnk = link_input.get()
global qr_img
qr = qrcode.QRCode(version=1, error_correction = qrcode.constants.ERROR_CORRECT_L, box_size=10, border=3)
qr.add_data(lnk)
qr.make(fit=True)
time_str = str(int(time.time()))
img = qr.make_image(fill_color='cyan', back_color='#2c3e50')
img.save(f'qrcode_{time_str}.png')
qr_img = f'qrcode_{time_str}.png'
return qr_img
def show_qr():
global qr_img
qr_img = ImageTk.PhotoImage(Image.open(qr_img))
qr = tk.Label(frame, image = qr_img)
qr.grid(row =3, columnspan = 3, padx = 5, pady = 5)
qr.config(image = qr_img)
return qr_img
l1 = tk.Label(root, text = "Welcome to QR Code Generator", font=("Calibre", 16), bg="#2c3e50", fg="white")
l1.grid(row =0, columnspan = 2, padx = 5, pady = 5)
frame = tk.Frame(root)
frame.grid()
frame.config(bg="#2c3e50")
l2 = tk.Label(frame, text = "Link you want as a QR Code: ", bg="#2c3e50", fg="white")
l2.grid(row =1, column = 1, padx = 5, pady = 5, sticky="w")
link_name = tk.StringVar(frame, value='hhtps://')
e1 = tk.Entry(frame, textvariable = link_name, width=35)
e1.grid(row =1, column = 2, padx = 5, pady = 5)
b_cre = tk.Button(frame, text = 'Create QR Code', command = lambda: create_QR(link_name))
b_cre.grid(row =2, column = 1, padx = 5, pady = 5)
b_sav = tk.Button(frame, text = 'Show QR Code', command = show_qr)
b_sav.grid(row =2, column = 2, padx = 5, pady = 5)
root.mainloop()
Output:
I made a program that converts 1 currency to another(in this case only won to dollars). However, when I try to click on US radio button, it says "could not convert string to float: '' ". So, what's the problem here? I tried to run it without an additional window, and it worked perfectly fine, but when I open a converter window in a new window, it does not work. What is the problem and how do I make it so the converter would work fine when you open it in a new window?
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showerror
from tkinter import *
root = tk.Tk()
root.geometry('5000x5000')
def openconverter():
root = tk.Tk()
root.title('Change Converter')
root.geometry('400x210')
def won_to_dollar(f):
US = 0.00079
return f*US
frame = ttk.Frame(root)
options = {'padx': 5, 'pady': 5}
won = tk.StringVar()
won_entry = ttk.Entry(frame, textvariable=won)
won_entry.grid(column=1, row=0, **options)
def convert_button_clicked(won_to_dollar):
try:
f = float(won.get())
c = won_to_dollar(f)
result = f'{f} won = {c:.2f}'
result_label.config(text=result)
except ValueError as error:
showerror(title='Error', message=error)
result_label = ttk.Label(frame)
result_label.grid(row=1, columnspan=3, **options)
frame.grid(padx=10, pady=10)
r = IntVar()
Radiobutton(root, text="US", variable = r, value = 1, command = lambda : convert_button_clicked(won_to_dollar)).place(x = 220, y = 20)
myLabel = Label(root, text = r.get())
myLabel.grid
root.mainloop()
Converted = Button(root, text="converter",font = ("Helvetica", 15), width=50, height=50, compound="c", activeforeground = "green", command = lambda: openconverter())
Converted.place(x=10, y=185)
root.mainloop()
Try this and click convert and enter value and select US.
from tkinter import ttk
from tkinter.messagebox import showerror
from tkinter import *
root = Tk()
root.title('Change Converter')
root.geometry('400x810')
def openconverter():
def won_to_dollar(f):
US = 0.00079
return f*US
frame = Frame(root)
options = {'padx': 5, 'pady': 5}
won = StringVar()
won_entry = Entry(frame, textvariable=won)
won_entry.grid(column=1, row=0, **options)
def convert_button_clicked(won_to_dollar):
try:
f = won.get()
c = won_to_dollar(float(f))
result = f'{f} won = {c}'
result_label.config(text=result)
except ValueError as error:
showerror(title='Error', message=error)
result_label = Label(frame)
result_label.grid(row=1, columnspan=3, **options)
frame.grid(padx=10, pady=10)
r = IntVar()
Radiobutton(root, text="US", variable = r,
value = 1,
command = lambda : convert_button_clicked(won_to_dollar)).place(x = 220, y = 20)
myLabel = Label(root, text = r.get())
myLabel.grid
Converted = Button(root, text="converter",
font = ("Helvetica", 15), width=50, height=50, compound="c",
activeforeground = "green", command = lambda: openconverter())
Converted.place(x=10, y=5)
root.mainloop()
from tkinter import *
root = Tk()
root.title("Tournament")
root.geometry("360x100")
def Choice():
second = Toplevel()
second.title("Tournament")
second.geometry("360x100")
command = root.withdraw()
typechoice = Label(second, text = "Are you part of a Team or Solo?")
typechoice.grid(row=0,column=0)
solo1 = Button(second, text = "Solo", command = Soloscreen)
solo1.grid(row=1,column=0)
team1 = Button(second, text = "Team", command = Teamscreen)
team1.grid(row=2,column=0)
def Soloscreen():
third = Toplevel()
third.title("Tournament")
third.geometry("360x100")
typechoice = Label(third, text="Enter your name")
typechoice.grid(row=0, column=0)
done = Button(third, text="Done")
done.grid(row=1, column=0)
def Teamscreen():
fourth = Toplevel()
fourth.title("Tournament")
fourth.geometry("360x100")
typechoice = Label(fourth, text="Enter your name")
typechoice.grid(row=0, column=0)
done = Button(fourth, text="Done")
done.grid(row=1, column=0)
# Creating GUI widgets
Start = Button(root, text="Start",width = "30", command=Choice, fg="red")
PHS = Button(root, text="Previous High Scores", width = "30", fg="red")
ENQ = Button(root, text="Enter New Questions", width = "30", fg="red")
# Displaying them on screen
Start.grid(row = 1, column = 3)
PHS.grid(row = 2, column = 3)
ENQ.grid(row = 3, column = 3)
root.mainloop()
As you can see here I have a pretty simple multiple window set up currently, what I dont understand is that I'm able to close the Root window with command = root.withdraw()however under the Soloscreen and Teamscreen windows the same command but changed to close the Choice screen wont seem to work?
I am creating a word editor in which I would like a taskbar at the top which has an OptionMenu widget with 3 possible choices - "right", "left", and "center". When one of these choices are chosen, it should take the value of that choice and set a text box window to each of those values using .tag_add, .insert, and .tag_config. Here is my code so far. All of it is inside of a frame called Task1, and the text box itself is inside a frame called label_frame. Next, the taskbar and the OptionMenu widget is inside a frame called Taskbar1. Here is my full code, which makes the GUI work.
from tkinter import *
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
import tkinter as tk
from tkinter import Menu, filedialog
root = Tk()
class ToDoList(tk.Frame):
def __init__(self, master):
root.columnconfigure(2, weight=1)
root.rowconfigure(1, weight=1)
root.title("To - Do List")
root.geometry("1200x600")
root.configure(background = "white")
# Variable list:
style = ttk.Style()
current_theme =style.theme_use()
style.theme_settings(current_theme, {"TNotebook.Tab": {"configure": {"padding": [20, 5], "background" : "white"}}})
style.theme_settings(current_theme, {"TNotebook" : {"configure" : {"tabposition" : "wn", "padding" : (0, 5)}}})
style.theme_settings(current_theme, {"TNotebook.Window" : {"configure" : {"width" : 500}}})
TasksList = ttk.Notebook(root)
Task1 = tk.Frame(TasksList, bg='white', height = 1000, width = 3000)
Taskbar1 = tk.Frame(Task1, bg="white", width=176)
Taskbar1.pack()
Button(Taskbar1, text="Hello", highlightthickness=0, borderwidth=0, highlightbackground = "white").pack(pady=[4, 5], padx=[3,3], ipadx = [2], ipady = [2], side = LEFT)
JustifyOptionList = ["right", "center", "left"]
JustifyDefaultOption=StringVar(Taskbar1)
JustifyDefaultOption.set(JustifyOptionList[0]) # default choice
JustifyOption= OptionMenu(Taskbar1, JustifyDefaultOption, *JustifyOptionList)
JustifyOption.pack(side = LEFT)
JustifyDefaultOption
entry1 = Entry(Task1, width = 60, font = "Calibri 20", highlightthickness = 0, justify = "center", selectborderwidth = 0, bd = 1, borderwidth = 0, relief = FLAT)
entry1.pack()
label_frame = tk.Frame(Task1, width=1000,height=550,bg="blue")
label_frame.pack()
label_frame.columnconfigure(0, weight=2)
label_frame.rowconfigure(0, weight = 1)
label_frame.pack_propagate(0)
# create a Text widget
root.txt = tk.Text(label_frame)
root.txt.config(font=("TkMenuFont"), undo=True, wrap='word', highlightthickness=0, borderwidth=0, bd = 1, highlightbackground = "white", spacing1 = 5, spacing2 = 5, spacing3 = 5)
root.txt.tag_config(JustifyDefaultOption.get(), justify = JustifyDefaultOption.get())
root.txt.insert("1.0", "Please enter your notes here")
root.txt.tag_add(JustifyDefaultOption.get(), "1.0", "end")
root.txt.pack(expand=TRUE, fill = "both", side = LEFT)
# create a Scrollbar and associate it with txt
scrollb = tk.Scrollbar(label_frame, command=root.txt.yview, width = 16, bg = "white", troughcolor = "white", highlightbackground = "white")
scrollb.pack(fill = Y, side = RIGHT)
root.txt['yscrollcommand'] = scrollb.set
Task2 = tk.Frame(TasksList, bg='white')
text=ScrolledText(Task2, width = 176, height = 120, font = "TkMenuFont")
text.grid(row = 2, column = 0)
entry2 = Entry(Task2, width = 179, font = "TkMenuFont")
entry2.grid(row=0, column=0, sticky = W)
Task3 = tk.Frame(TasksList, bg = "white")
text=ScrolledText(Task3, width = 176, height = 120, font = "TkMenuFont")
text.grid(row = 2, column = 0)
entry3 = Entry(Task3, width = 179, font = "TkMenuFont")
entry3.grid(row=0, column=0, sticky = W)
TasksList.add(Task1,text = 'Click Here In Order To Read The Instructions')
TasksList.add(Task2, text = 'Two Two Two Two Two Two'[0: 40] + '...')
TasksList.add(Task3, text = "Three Three Three Three Three Three Three Extra"[0 : 40] + '...')
TasksList.grid(row=1, column=0, sticky=N+W, columnspan=3)
Button(root, text = "WELCOME", borderwidth=0, highlightthickness=0).grid(row=0, column=1, sticky=E, ipady = [5])
Label(text="HELLO", borderwidth=0, highlightthickness=0).grid(row=0, column=0, sticky=W, ipady = [5])
root.mainloop()
The part that I am confused about regarding this is the fact that even though I have a OptionList that records the option that the user selects, this option is not set in the justify settings even though I am using a .get function to take the user's justify setting and apply it to the text box.
The problem is that you do not change the justify setting each time the option changes. Initializing with .get does not make the value update when the StringVar value changes.
One way of applying the new justify setting to the text is to use the command option of the OptionMenu to do it:
import tkinter as tk
def justify_text(option):
"""Change text justify setting."""
text.tag_configure('justify', justify=option)
# make sure all text has the tag
text.tag_add('justify', '1.0', 'end')
root = tk.Tk()
options = ["right", "center", "left"]
var = tk.StringVar(root, options[0])
menu = tk.OptionMenu(root, var, *options, command=justify_text)
menu.pack()
text = tk.Text(root)
text.insert('1.0', "Please enter your notes here", 'justify')
text.tag_configure('justify', justify=options[0])
text.pack()
root.mainloop()
I'm trying to get all of my labels and input boxes to be shifted down to the middle of the screen using the .pack() method. I tried using
anchor = CENTER
with the.place() method but that made everything overlap in the center. How can I simply shift all of my widgets to the center of my Tkinter frame?
Here's my code:
from Tkinter import *
root = Tk()
root.minsize(width = 500, height = 500)
root.wm_title("Email Program v1.0")
def callback():
print ("Hello!")
#sign in - email
usernameLabel = Label(root, text = "Email:")
usernameLabel.pack(padx = 0, pady = 0)
usernameInput = Entry(root)
usernameInput.pack()
usernameInput.focus_set()
passwordLabel = Label(root, text = "Password:")
passwordLabel.pack()
passwordInput = Entry(root, show = "*", width = 20)
passwordInput.pack()
passwordInput.focus_set()
#submit email credentials - connect to the server
submitEmail = Button(root, text = "Submit", fg = "black", width = 10, command = callback)
submitEmail.pack()
root.mainloop()
I managed to put those labels and entries to the center using three frames, two without any content just to 'eat' space.
frame1 = Frame(root)
frame1.pack(expand=True)
frame2 = Frame(root)
usernameLabel = Label(frame2, text = "Email:")
usernameLabel.pack(padx = 0, pady = 0)
usernameInput = Entry(frame2)
usernameInput.pack()
usernameInput.focus_set()
passwordLabel = Label(frame2, text = "Password:")
passwordLabel.pack()
passwordInput = Entry(frame2, show = "*", width = 20)
passwordInput.pack()
passwordInput.focus_set()
submitEmail = Button(frame2, text = "Submit", fg = "black", width = 10, command\
= callback)
submitEmail.pack()
frame2.pack(anchor=CENTER)
frame3 = Frame(root)
frame3.pack(expand=True)
The simple solution is to put all the widgets in a frame, and then center the frame.