I have two functions and two GUI.
I cannot get them to work after each other.
first, I want to open my browse GUI then editing GUI.
help me out, please.
from tkinter import *
from tkinter import filedialog
window = Tk()
def fileme():
root = Tk()
root.withdraw()
file_path = filedialog.askopenfilenames(filetypes=[("Text file","*.txt")])
print(file_path)
window.withdraw()
with open(file_path[0]) as f:
f_contents = f.read()
b=(f_contents)
print(b)
window.title('Edit and save text files by Ali')
frame = Frame(window)
btn = Button(frame, text = 'Browse', command= fileme)
btn.pack(side = RIGHT , padx =55)
frame.pack(padx=100,pady = 30)
root=Tk()
x=filedialog.askopenfilename(filetypes=[("Text file","*.txt")])
T=Text(root,state='normal', height=20, width=70)
T.pack()
T.insert(END, open(x).read())
def save():
b = T.get('1.0', END)
f = open(x, 'wt')
f.write(b)
f.close()
btn= Button(root, text='Save', command=save)
btn.pack(side = RIGHT , padx =55)
window.mainloop()
root.mainloop()
I figured it out
Here is an answer to this type of questions.
hope to be useful for anyone who is learning programming.
from tkinter import *
from tkinter import filedialog
window=Tk()
def x():
x=filedialog.askopenfilename(filetypes=[("Text file","*.txt")])
T = Text(window, state='normal', height=20, width=70)
T.pack()
T.insert(END, open(x).read())
def save():
b = T.get('1.0', END)
f = open(x, 'wt')
f.write(b)
f.close()
btn1 = Button(window, text='Save', command=save)
btn1.pack(side=RIGHT, padx=55)
window.title('Edit and save text files by Ali')
frame = Frame(window)
btn = Button(frame, text = 'Browse', command= x)
btn.pack(side = RIGHT , padx =55)
frame.pack(padx=100,pady = 30)
window.mainloop()
#Epiphnac In your solution both the browser window and the text editor open in the same window. I think my solution is a little bit better than that.
I have put the editor inside a new window using Toplevel.
Like this:
import tkinter as tk
from tkinter import filedialog
window = tk.Tk()
def editor():
x = filedialog.askopenfilename(filetypes=[("Text file", "*.txt")])
new_window = tk.Toplevel()
t = tk.Text(new_window, state='normal', height=20, width=70)
t.pack()
t.insert(tk.END, open(x).read())
def save():
b = t.get('1.0', tk.END)
f = open(x, 'wt')
f.write(b)
f.close()
btn1 = tk.Button(new_window, text='Save', command=save)
btn1.pack(side=tk.RIGHT, padx=55)
window.title('Edit and save text files by Ali')
frame = tk.Frame(window)
btn = tk.Button(frame, text='Browse', command=editor)
btn.pack(side=tk.RIGHT, padx=55)
frame.pack(padx=100, pady=30)
window.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 keep getting an error saying that the button failed to call the function when I press it here is the function it's failing to run
import re
from tkinter import *
from tkinter import ttk
import time
from turtle import bgcolor
import webbrowser
from tkinter import messagebox
from tkinter import filedialog
root = Tk()
root.title('Notepad')
root.iconbitmap('C:/Users/Hero/Documents/Visual Studio code/My project/notes.ico')
root.geometry("640x500")
root.tk.call("source", "C:/Users/Hero/Documents/Visual Studio code/My project/azure.tcl")
root.tk.call("set_theme", "dark")
global x
x = 20
def change_theme():
if root.tk.call("ttk::style", "theme", "use") == "azure-dark":
root.tk.call("set_theme", "light")
else:
root.tk.call("set_theme", "dark")
def increase_font_size():
global x
global f
x = x + 1
print(x)
text.config(font=(f, x))
def decrease_font_size():
global x
global f
x = x - 1
print(x)
text.config(font=(f, x))
def pfonts():
font_page = Tk()
font_page.title('Fonts')
font_page.geometry('295x200')
font_page.configure(bg='#292929')
font_page.tk.call("source", "C:/Users/Hero/Documents/Visual Studio code/My project/azure.tcl")
font_page.tk.call("set_theme", "dark")
global f
fentry1 = ttk.Entry(font_page, width=80)
fentry1.pack()
label1 = Label(font_page, text='Enter the font name you want', font=("Tekton Pro", 17), bg='#292929')
label2 = Label(font_page, text='warning: caps lock sensitive', font=("Tekton Pro", 8), bg='#292929')
label1.pack()
label2.pack(side=BOTTOM)
def change_font():
global f
f = fentry1.get()
text.config(font=(f, x))
print(f)
bbfont = ttk.Button(font_page, text='Confirm font', command=change_font)
bbfont.pack(side=BOTTOM)
def killer():
print("killing the instence")
root.destroy()
def savefile():
global filename
filename = filedialog.asksaveasfilename(initialdir='/', title='Save File', filetypes=(('Text Files', '*.txt'), ('All Files', '*.*')))
textContent = text.get("1.0",END)
textContent = str(textContent)
myfile = open(filename, "w+")
myfile.write(textContent)
style=ttk.Style()
style.theme_use('azure-dark')
style.configure("Vertical.TScrollbar", background="grey", bordercolor="black", arrowcolor="white")
barframe = Frame()
barframe.pack(side=BOTTOM)
bfonts = ttk.Button(barframe, text='Fonts', style='Accent.TButton', command=pfonts)
open = ttk.Button(barframe, text='Open', style='Accent.TButton')
save = ttk.Button(barframe, text='Save', style='Accent.TButton', command=savefile)
close = ttk.Button(barframe, text='Close', style='Accent.TButton', command=killer)
#fonts = ttk.Entry(barframe, width=10)
calculater = ttk.Button(barframe, text='Calculater', width=10, style='Accent.TButton')
calander = ttk.Button(barframe, text='Calander', width=10, style='Accent.TButton')
increase_size = ttk.Button(barframe, text='+', width=2, command=increase_font_size)
decrease_size = ttk.Button(barframe, text='-', width=2, command=decrease_font_size)
bfonts.grid(row=0, column=0)
open.grid(row=0, column=1)
save.grid(row=0, column=2)
close.grid(row=0, column=3)
#fonts.grid(row=0, column=1)
calculater.grid(row=0, column=4)
calander.grid(row=0, column=5)
increase_size.grid(row=0, column=6)
decrease_size.grid(row=0, column=7)
scroll = ttk.Scrollbar(root, orient='vertical')
scroll.pack(side=RIGHT, fill='y')
text=Text(root, font=("Georgia", x), yscrollcommand=scroll.set, bg='#292929', height=1, width=1)
scroll.config(command=text.yview)
text.pack(fill=BOTH, expand=1)
root.mainloop()
Error code
Traceback (most recent call last):
File "C:\Users\Hero\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "c:\Users\Hero\Documents\Visual Studio code\My project\MainFrame.py", line 82, in savefile
myfile = open(filename, "w+")
TypeError: 'Button' object is not callable
thats everything the whole script and the whole error i hope that helps i just thought it would get in the way if i posted the whole code as its really big lol
After testing it, the problem was you assigning a predefined python variable to the open button. Where you have:
open = ttk.Button(barframe, text='Open', style='Accent.TButton')
Just change that to something like:
openButton = ttk.Button(barframe, text='Open', style='Accent.TButton')
And then downstream change to this:
openButton.grid(row=0, column=1)
I'm new to coding and I'm trying to grab an input from an entry using tkinter in python. In theory, I should click the 'upload' button, then the code will get the entry and print it for me, but this isn't working. This is my code.
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
def cancel():
quit()
def upload():
Entry.get()
print(Entry)
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
whitebutton = Entry(frame, fg="black")
whitebutton.pack( side = TOP)
redbutton = Button(frame, text="Cancel", fg="red", command = cancel)
redbutton.pack( side = LEFT)
bluebutton = Button(frame, text="Upload URL", fg="blue", command = upload)
bluebutton.pack( side = RIGHT )
root.mainloop()
Does anyone know what's going wrong here?
Thanks, Kieran.
Entry is a class in __init__ file in tkinter folder.
Instead of this:
Entry.get()
print(Entry)
This is what you need
var=whitebutton.get()
print(var)
First of all, it is better to use Tkinter variables rather than normal python variables. Here you need to use StringVar() to set and get an user input from entry. So the complete code -
from tkinter import *
root = Tk()
var = StringVar()
frame = Frame(root)
frame.pack()
def cancel():
quit()
def upload():
print(var.get())
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
whitebutton = Entry(frame,textvariable=var ,fg="black")
whitebutton.pack( side = TOP)
redbutton = Button(frame, text="Cancel", fg="red", command = cancel)
redbutton.pack( side = LEFT)
bluebutton = Button(frame, text="Upload URL", fg="blue", command = upload)
bluebutton.pack( side = RIGHT )
root.mainloop()
For more info - this and this
put root var before root.mainloop()
and make app var and put into "Application(root)"
then change ""root".mainloop()" to "app.mainlop()"
import tkinter as tk
// your code
root = tk.Tk()
app = Application(root)
app.mainloop()
Just a simple example of a problem I experienced:
from tkinter import *
root = Tk()
frame = Frame(root)
label = Label(frame, text = "Hey")
label.pack()
def packframe():
frame.pack()
def destroyframe():
frame.destroy()
pack_button = Button(root, text = "pack", command = packframe)
pack_button.pack()
des_button = Button(root, text = "destroy", command = destroyframe)
des_button.pack()
Once I press the destroy button, I cannot pack it back again on the screen with the pack_button. Im not sure why is it so, but I would appreciate both explanaition and a solution
below is my code for creating a tool that takes a file path, stores the value, and then opens the specific file path selected by the user.
Currently, I'm looking to take the user entry mypathEntry that is stored in the mypathList listbox after clicking the Save button and add a command to it. The command will open that selected file path. My current code returns an error message regarding mypathList.add_command(command=Open) stating that Listbox instance has no attribute 'add_command'.
What is the syntax for adding a command to a listbox item?
from Tkinter import *
import os
root = Tk()
def Save():
fp = mypathEntry.get()
scribe = open('filepath.txt', 'w')
scribe.write(fp)
mypathEntry.delete(0, 'end')
mypathList.insert(1, fp)
def Open():
path = fp
menu = Menu(root)
##root.config(menu=menu)
##subMenu = Menu(menu)
##menu.add_cascade(label="Filepaths", menu=subMenu)
##subMenu.add_command(command=Save)
mypathLabel = Label(root, text="Copy and Paste your filepath here:")
mypathEntry = Entry(root, bg="black", fg="white", relief=SUNKEN)
mypathSaveButton = Button(root, text="Save Path", bg="black", fg="white", command=Save)
mypathList = Listbox(root, bg="black", fg="white")
mypathList.add_command(command=Open)
mypathLabel.pack()
mypathEntry.pack()
mypathSaveButton.pack()
mypathList.pack()
root.mainloop()
According to this,
http://effbot.org/tkinterbook/listbox.htm
The listbox item does not have a command option. So what you need to do instead is to bind an event to it. Here is a complete working example.
from tkinter import *
import os
root = Tk()
class MainGui:
def __init__(self, master):
self.mypathLabel = Label(master, text="Copy and Paste your filepath here:")
self.mypathEntry = Entry(master, bg="black", fg="white", relief=SUNKEN)
self.mypathSaveButton = Button(master, text="Save Path", bg="black", fg="white", command=self.save_path)
self.mypathList = Listbox(master, bg="black", fg="white")
self.mypathLabel.pack()
self.mypathEntry.pack()
self.mypathSaveButton.pack()
self.mypathList.pack()
self.mypathList.bind("<Double-Button-1>", self.open_path)
def save_path(self):
fp = self.mypathEntry.get()
self.mypathEntry.delete(0, 'end')
self.mypathList.insert(1, fp)
def open_path(self, event):
list_item = self.mypathList.curselection()
fp = self.mypathList.get(list_item[0])
print(fp)
try:
with open(fp, 'r') as result:
print(result.read())
except Exception as e:
print(e)
MainGui(root)
root.mainloop()