Cant get listbox to show for tkinter - python

So, what I am trying to do is open a file when pressing a button and displaying the contents in a listbox. This is what I have so far, but I am not getting the listbox to display, let alone get the info to be in the listbox:
#!/usr/bin/perl -w
import time
from Tkinter import *
import tkFileDialog
def listbox(listbox):
def open_file():
file = tkFileDialog.askopenfilename()
openFile = open(file)
for line in openFile:
listbox.insert(END, line)
open_file()
class App:
def __init__(self, parent):
frame = Frame(parent.title("Buttons"))
frame.pack()
root.pack_propagate(0)
self.exit = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.exit.pack(side=LEFT)
self.open = Button(frame, text="Open...", command=self.call_listbox)
self.open.pack(side=LEFT)
frame.listbox = Frame()
scrollme = Scrollbar(frame.listbox)
self.listbox = Listbox(frame.listbox, yscrollcommand = scrollme.set)
scrollme.config(command = self.listbox.yview)
scrollme.pack(side = RIGHT, fill = Y)
self.listbox.pack()
self.listbox.insert(END, "Code:")
def call_listbox(self):
listbox(self.listbox)
root = Tk()
app = App(root)
root.mainloop()
any suggestions? thanks

You are forgetting to pack the frame that contains the listbox.
FWIW, your overloading of the name "listbox" makes your code very confusing - you have def listbox(listbox), self.listbox and frame.listbox. And you also have call_listbox and the Listbox class to add to the confusion.

Related

Dynamic dictionary entry tkinter

I'm trying to make a basic GUI in tkinter but I want it to be dynamic.
The end goal is to have a nested dictionary populated by this GUI and that the user can add as many items as he/she want.
I managed to enter a full single dictionary with some simple (and pretty repetetive) code:
for example:
Edit
from Tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()
Now im looking for a way for the GUI to have a button (like a + sign) that will allow the user to open another single or a set of entries each time he/she presses the button and populate the dictionary accordingly.
Any Ideas?
You basically want to have a Label & Entry object. You can collect these objects in a collection type such as list or dict.
The example below does that using a list:
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
class LabelEntry(tk.Frame):
def __init__(self, master, text="User Name", *args, **kwargs):
tk.Frame.__init__(self, master, *args, **kwargs)
self._label = tk.Label(self, text=text)
self._entry = tk.Entry(self, bd=5)
self._label.pack(side='left', fill='both', expand=True)
self._entry.pack(side='left', fill='both', expand=True)
def add_a_le(master, widgets_list):
widgets_list.append(LabelEntry(master))
widgets_list[-1].pack()
def main():
root = tk.Tk()
my_label_entries = list()
add_btn = tk.Button(root, text="Add")
add_btn['command'] = lambda m=root, ws=my_label_entries: add_a_le(m, ws)
add_btn.pack(side='bottom')
tk.mainloop()
if __name__ == '__main__':
main()

import user input from TKinter button to a different .py module

On ticket.py module i have a Tkinter frame; value = Entry(frame), and on the same module I have a button where command=exoutput;
def exoutput():
print value.get()
I would like to import the value to othermodule.py on the button command/ when I hit the button.
Currently when I import, the print is generated from the exoutput() function, rather than from the othermodule.py file.
Suggestions on how to print the value on othermodule.py?
# ticket.py
from Tkinter import*
window = Tk()
window.title("Entry")
frame = Frame(window)
value = Entry(frame)
def exoutput():
print value.get()
btnStage = Button(frame, text='ACTION', command=exoutput)
btnStage.pack(side=RIGHT, padx=2)
value.pack(side=LEFT)
frame.pack(padx=10, pady=10)
window.resizable(0, 0)
window.mainloop()
The other file, I've tried something like this;
# othermodule.py
import ticket
usersinput = ticket.value.get()
print usersinput
I think you either need multi-threading, or swap your file contents. Nothing runs after mainloop until the Tk instance is destroyed.
Alternatively, you could structure your ticket.py in OOP, and fetch GUI object from it by your othermodule to use it as you please. Below is an example:
ticket.py:
#import tkinter as tk
import Tkinter as tk
class Window(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title("Entry")
self.resizable(False, False)
# create widgets
self.frame = tk.Frame(self)
self.value = tk.Entry(self.frame)
self.btn_stage = tk.Button(self.frame, text="ACTION")
# widgets layout
self.frame.pack(padx=10, pady=10)
self.btn_stage.pack(side='right', padx=2)
self.value.pack(side='left')
if __name__ == "__main__":
root = Window()
root.mainloop()
and othermodule.py:
import ticket
def put():
global my_var_in_othermodule
my_var_in_othermodule = ticket_GUI.value.get()
ticket_GUI.destroy()
my_var_in_othermodule = ""
ticket_GUI = ticket.Window()
ticket_GUI.btn_stage['command'] = put
ticket_GUI.mainloop()
print(my_var_in_othermodule)
input()

How to make Tkinter button to be placed in particular position?

I am new to python so I was trying to make a GUI, in that I have to place a button in a particular position.
I tried using self.nxt_form.place(x=200,y=100) instead of self.nxt_form.pack().
But the button disappeared and only the frame appeared when it ran. Can you tell me how to place the button in a particular position?
Here is the code:
import tkinter as tk
class Main_form:
def __init__(self, root,title="Simulated MTBF"):
self.root = root
self.frame = tk.Frame(self.root)
"""Button nxt_form which moves to next form"""
self.nxt_form = tk.Button(self.frame, text = 'Next Form', width = 25,command = self.new_window)
self.nxt_form.pack()
self.frame.pack()
"""command to open new window by clicking Button """
def new_window(self):
self.newWindow = tk.Toplevel(self.root)
self.app = Demo2(self.newWindow)
class Demo2:
def __init__(self, root):
self.root = root
self.frame = tk.Frame(self.root)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.root.destroy()
def main():
root = tk.Tk()
app = Main_form(root)
root.mainloop()
if __name__ == '__main__':
main()
when i am using tkinter i used column and row to position objects
self.btn = tk.Button(self, text = "button")
self.btn.grid(row = 1, column = 1)
EDIT - expanded on information in response to comment (below)
I would make an label and change its width and height to make the spacing you need (note im a beginer at python as well so this is probly a bad way but it works)
from tkinter import *
import tkinter as tk
from tkinter.ttk import Combobox,Treeview,Scrollbar
class MainMenu(Frame):
def __init__(self, master):
""" Initialize the frame. """
super(MainMenu, self).__init__(master)
self.grid()
self.create_GUI()
def create_GUI(self):
frame1 = tk.LabelFrame(self, text="frame1", width=300, height=130, bd=5)
frame1.grid(row=0, column=0, columnspan=3, padx=8)
#the frame is not needed but it is a good thing to use as can group
#parts of your interface together
self.text1 = Entry(frame1)
#note if you were not using frames would just put self here
self.text1.grid(row = 1, column = 0)
self.text2 = Label(frame1, text = "",height = 10)
self.text2.grid(row = 2 , column = 0)
self.text3 = Entry(frame1)
self.text3.grid(row = 3, column = 0)
root = Tk()
root.title("hi")
root.geometry("500x500")
root.configure(bg="white")
app = MainMenu(root)
root.mainloop()
Also note that you can not use pack and grid together what you could do is group your objects in different frames then use grid in one frame and pack in a different frame. I personally prefer to use grid to pack as it gives you more control over your object then pack does

python tkinter to display File and Save

I have created an coding gui,which doesnot show 'File' and 'save' in the Gui
Please help me to fix my problem.
I have created a Function for File and Save ,still not working!
please help me to rectify my code!
from tkinter import *
import tkinter.messagebox
import tkinter
import tkinter as tki
import tkinter.filedialog as th1
import re
class App(object):
def __init__(self,root):
self.root = root
# create a Frame for the Text and Scrollbar
txt_frm = tki.Frame(self.root, width=600, height=400)
txt_frm.pack(fill="both", expand=True)
# ensure a consistent GUI size
txt_frm.grid_propagate(False)
# create first Text label, widget and scrollbar
self.lbl1 = tki.Label(txt_frm, text="Type")
self.lbl1.grid(row=0,column=0,padx=2,pady=2)
self.txt1 = tki.Text(txt_frm, borderwidth=3, relief="sunken", height=4,width=55)
self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
self.txt1.grid(row=0, column=1, sticky="nsew", padx=2, pady=2)
scrollb1 = tki.Scrollbar(txt_frm, command=self.txt1.yview)
scrollb1.grid(row=0, column=2, sticky='nsew')
self.txt1['yscrollcommand'] = scrollb1.set
button = tki.Button(txt_frm,text="Clickone", command = self.retrieve_input)
button.grid(column=2,row=0)
button1 = tki.Button(txt_frm,text="Cli", command = self.clearBox)
button1.grid(column=2,row=0)
def retrieve_input(self):
input1 = self.txt1.get("0.0",'end-1c')
with open('text.txt','a+') as f:
f.write(input1+'\n')
f.close()
def clearBox(self):
self.txt1.delete('1.0', 'end')#<-0.0/1.0
def file_save():
f = th1.asksaveasfile(mode='w', defaultextension=".txt")
if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
return
text2save = str(text.get(1.0, END))
a= (f)
f.write(text2save)
f.close()
root = tki.Tk()
menubar=Menu(root)
filemenu=Menu(menubar,tearoff=0)
filemenu.add_command(label="Save", command=file_save)
app = App(root)
root.mainloop()
Please help!Answers will be appreciated!
You aren't adding the menubar to the window. Add this after you create the menubar.
root.configure(menu=menubar)
You then also have to add the file menu to the menubar:
menubar.add_cascade(label="File", menu=filemenu)

Tkinter: Pack new widgets below other widgets

I'm trying to pack the button below the Text and Scrollbar widget.
#!/usr/bin/python
try:
from Tkinter import *
except ImportError:
from tkinter import *
class Chat(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.pack(anchor=N, fill=BOTH)
self.create_widgets()
self.count = 0
def create_widgets(self):
self.scrolly = Scrollbar(self)
self.scrolly.pack(side=RIGHT, fill=Y)
self.chattext = Text(self, borderwidth=5, yscrollcommand=self.scrolly.set)
self.chattext.pack(side=LEFT)
self.scrolly.config(command=Text.yview(self.chattext))
self.button1 = Button(self, text="Add text", command=self.add_text)
self.button1.pack()
def add_text(self):
self.count += 1
self.chattext.insert("end", "%i\n" % self.count)
self.chattext.update_idletasks()
def main():
root = Tk()
root.title("Test Chat Client")
root.geometry("600x500")
#root.resizable(0,0)
app = Chat(root)
root.mainloop()
if __name__ == "__main__":
main()
This is what it looks like
I want the button to be below and not in between the other widgets.
I have tried the following:
self.button1.pack(after=self.scrolly)
self.button1.pack(after=self.chattext)
How may i pack the button at the bottom?
Another issue is that the scrollbar does not work, when i try to scroll nothing happens.
(Yes, i have tried to fill the Text widget with alot of lines, more than it can view.)
Also, why is the scrollbar viewed/packed outside/"far" away from the Text widget?
Try using the grid geometry manager instead.
http://www.tkdocs.com/tutorial/grid.html
I think you should consider replacing the text field with a ScrolledText field.
It's a lot easier to use and doesn't require manual scrollbar placement.
(Don't use pack to place it though. Use grid)
import tkinter as tk
import tkinter.scrolledtext as tkst
self.chattext = tkst.ScrolledText(
master = self,
wrap = tk.WORD,
width = 20,
height = 10
)

Categories