Update textbox with text from browsed file. python - python-2.7

I am currently using Python 2.7 and Tkinter. I have a button that browses my directory and takes the file's directory location and saves it to filename. I would like this to change the value of inputBox to the value of filename automatically when the file is chosen.
import os
from Tkinter import *
import tkFileDialog
root = Tk()
root.title("Doc Word Frequency")
root.geometry("600x300")
def close_window ():
root.destroy()
def browse_directory():
filename = tkFileDialog.askopenfilename()
print(filename)
#Change value of inputBox
inputBox = Entry(root, width = 50)
inputBox.grid(row = 0, column = 0, padx = 20, pady = 20)
inputBox.insert(END, '"Upload Document File"')
inputBox.config(state = DISABLED)
Button(root, width = 9, text = 'Browse', command = browse_directory).grid(row = 0, column = 1, sticky = W, padx = 4)
Button(root, width = 9, text = 'Upload').grid(row = 0, column = 2, sticky = W, padx = 4)
Button(root, width = 9, text = 'Quit', command = close_window).grid(row = 0, column = 3, sticky = W, padx = 4)
mainloop( )
PS. I am quite new to Python and any constructive criticism would be appreciated.

You can insert text into an entry widget with the insert method.
def browse_directory():
filename = tkFileDialog.askopenfilename()
print(filename)
inputBox.configure(state=NORMAL)
inputBox.delete(0, "end")
inputBox.insert(0, filename)
inputBox.configure(state=DISABLED)

Related

Font size doubles unexpectedly in rmarkdown

The figure font size doubled unexpectedly between knits. Restarting R did not fix the issue. I ended up decreasing font size by 50% to fix the problem. Has this happened to anyone else? My theme is shown below.
style <- theme(plot.title = element_text(face = "bold", size = 30),
plot.subtitle = element_text(size = 30),
axis.title = element_text(size = 25, face="italic"),
axis.text = element_text(size = 25),
legend.text = element_text(size = 25),
legend.title = element_text(face = "bold", size = 25),
legend.position = "bottom",
panel.background = element_rect(fill = NA),
panel.grid.major = element_line(colour = "grey88"),
axis.ticks = element_line(color=NA),
axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)),
axis.title.x = element_text(margin = margin(t = 20, r = 0, b = 0, l = 0)))
If it changes between knits, maybe you were zoomed in on your web browser and didn't know it. it also might depend on your knit R chunks. if you can't replicate the issue, it might just be a random issue.

Have to import maya.cmds multiple times else maya forgets it after button press

as for some background, my code is most likely a complete mess, mostly since I've only had a couple of hours scripting in my life.
For class im creating a solar system with all the standard planets and also the option for the user to input their own planet. Everything worked fine up until i tried letting the user spawn the planets with a button in the UI(an ugly button for now but a button nonetheless). If the user presses a button, say 'Sun', then the sun spawns, but only once, if he then decides to spawn sun again or any other planet for that matter, it gives an error stating that the module doesn't contain 'polycube or polysphere'. So basically, the button works once, then doesn't work anymore. If i call them from anywhere but the button, it works perfectly and indefinitely. I figured since he doesn't know polycube or polysphere, its almost as if i didn't import maya.cmds, so lets try recalling it. and low and behold that works.
So basically my question is as follows, does maya forget its imported libraries when you press a button? and How do i solve this without having to re-import maya.cmds in every function?
import maya.cmds as maya
class create_body:
def __init__(self, distance, radius, bonus_scale, r, g, b):
import maya.cmds as maya
self.radius = radius * bonus_scale / 1000
self.bonusScale = bonus_scale
self.distanceScene = distance
self.distanceMeter = distance*1000000000
maya.polyCube()
self.r = r
self.g = g
self.b = b
def color_body_custom(self):
import maya.cmds as maya
value = maya.colorEditor()
self.color = [float(i) for i in value.split()]
self.r = self.color[0]
self.g = self.color[1]
self.b = self.color[2]
def spawn_body(self):
import maya.cmds as maya
maya.polySphere(r = self.radius)
maya.move(self.distanceScene, moveZ = True)
maya.move(0, 0, 0, ".scalePivot", ".rotatePivot", absolute=True)
maya.polyColorPerVertex(rgb=(self.r,self.g,self.b), colorDisplayOption=True)
def animate_body(self):
import maya.cmds as maya
orbitTimeYears = self.get_orbital_time()*10
key = str(orbitTimeYears) + 'sec'
maya.setKeyframe(v=0, at='rotateY', t=['0sec'], itt = 'spline', ott = 'spline')
maya.setKeyframe(v=-360, at='rotateY', t=[key], itt = 'spline', ott = 'spline')
maya.selectKey(attribute='rotateY')
maya.setInfinity(pri='linear', poi='linear')
def get_orbital_time(self):
import math
orbitMeter = self.distanceMeter * 2 * math.pi
gravConst = 132690600000000000000 / self.distanceMeter
orbitSpeed = math.sqrt(gravConst)
orbitTimeSec = orbitMeter / orbitSpeed
orbitTimeYears = orbitTimeSec / 31556926
return orbitTimeYears
class create_ui:
def __init__(self, window_name):
self.myPlanetarySystem = window_name
# Make sure there's only one window open by deleting the window if it exists
self.delete_ui()
# Create the UI
self.myp = maya.window(self.myPlanetarySystem)
maya.rowColumnLayout(numberOfColumns=3, columnWidth=[(1, 150), (2, 75), (3, 75)], columnOffset=[(1, 'left', 5)])
maya.showWindow()
maya.window(self.myPlanetarySystem, e=True, title='TileGenerator', w=200, h=190)
maya.button(label = 'Sun', command = partial(self.body, 0, 695.510, 10, True, 1, 1, 0))
maya.button(label='Mercury', command = partial(self.body, 57.9, 2.439, 1000, False, 0.2, 0.2, 0))
#Sun = create_body(0, 695.510, 10, 1, 1, 0)
#Sun.spawn_body()
#Mercury = create_body(57.9, 2.439, 1000, 0.2, 0.2, 0)
#Mercury.spawn_body()
#Mercury.animate_body()
#Venus = create_body(108.2, 6.051, 1000, .5, 0.2, 0)
#Venus.spawn_body()
#Venus.animate_body()
#Earth = create_body(149.6, 6.971, 1000, 0, 0, 1)
#Earth.spawn_body()
#Earth.animate_body()
#Mars = create_body(227.9, 3.389, 1000, 0.6, 0.1, 0)
#Mars.spawn_body()
#Mars.animate_body()
#Jupiter = create_body(778.5, 69.911, 100, 0.9, 0.8, 0.5)
#Jupiter.spawn_body()
#Jupiter.animate_body()
#Saturn = create_body(1433.4, 58.232, 100, 0.8, 0.8, 0.7)
#Saturn.spawn_body()
#Saturn.animate_body()
#Uranus = create_body(2876.6, 25.362, 100, 0.7, 0.8, 1.0)
#Uranus.spawn_body()
#Uranus.animate_body()
#Neptune = create_body(4503.4, 24.622, 100, 0.3, 0.4, 0.7)
#Neptune.spawn_body()
#Neptune.animate_body()
def delete_ui(self):
if maya.window(self.myPlanetarySystem, exists=True):
maya.deleteUI(self.myPlanetarySystem, window=True)
def body(self, distance, radius, bonus_scale, is_sun, r = 0.5, g = 0.5, b = 0.5, *args):
obj = create_body(distance, radius, bonus_scale, r, g, b)
obj.spawn_body()
if not is_sun:
obj.animate_body()
create_ui('myPlanetarySystem')
Answer: apparently importing my maya.cmds in the shorter version: maya conflicted with the program, i should've seen this coming. In other words, there's no more issues if I just import maya.cmds as cmds.

How to to add x,y labels in QGraphicsview using pyqt4

Here is my sample program. When I need to draw a line for x axis and y label for y axis .so can any one please help me how to add a line and lables to scene.i tried different ways but i didn't get the proper output.So please help me how to add labels to scene.Give me any suggestion to solve this task.Thank you in advance.
Given bellow is my tried code:
import sys
from pyface.qt import QtGui, QtCore
# class ScanView(QtGui.QGraphicsView):
# def __init__(self,X=5, Y=5,parent=None):
# super(ScanView, self).__init__(parent)
class DemoApp(QtGui.QMainWindow):
def __init__(self, parent=None):
super(DemoApp, self).__init__()
self.w= QtGui.QGridLayout()
self.v= QtGui.QGraphicsView()
self.w.addWidget(self.v)
self.widget = QtGui.QWidget()
self.widget.setLayout(self.w)
self.setCentralWidget(self.widget)
self._squares = []
n_rows, n_cols = 3, 2
squareLB = 50
label = QtGui.QLabel("xaxis")
label1 = QtGui.QLabel("yaxis")
self._scene = QtGui.QGraphicsScene()
mytext1 = QtGui.QGraphicsSimpleTextItem('label')
self._scene.addItem(mytext1)
mytext2 = QtGui.QGraphicsSimpleTextItem('label1')
self._scene.addItem(mytext2)
self.v.setScene(self._scene)
self.pen = QtGui.QPen(QtCore.Qt.DotLine)
self.pen.setColor(QtCore.Qt.red)
width, height = (2 + 2)*squareLB, (3 + 2)*squareLB
self._scene = QtGui.QGraphicsScene(0, 0, max(708, width), height)
p = squareLB if width > 708 else (708.0-2*squareLB)/2.0
for i in range(n_rows):
for j in range(n_cols):
it = self._scene.addRect(QtCore.QRectF(0,0,squareLB,squareLB),self.pen)
it.setPos(p + j*squareLB, i*squareLB)
self._squares.append(it)
self.v.setScene(self._scene)
class Settings(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Settings, self).__init__(parent)
self.folder = QtGui.QPushButton("Folder", clicked=self.showSettings)
central_widget = QtGui.QWidget()
self.setCentralWidget(central_widget)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.folder)
self.scrollArea = QtGui.QScrollArea(widgetResizable=True)
self.scrollArea.setBackgroundRole(QtGui.QPalette.Light)
hlay = QtGui.QHBoxLayout(central_widget)
hlay.addLayout(vbox)
hlay.addWidget(self.scrollArea)
self.setGeometry(200, 100, 300, 300)
def showSettings(self):
self.view = DemoApp()
self.newwidget = QtGui.QWidget()
hlay = QtGui.QHBoxLayout(self.newwidget)
hlay.addWidget(self.view)
self.scrollArea.setWidget(self.newwidget)
def main():
app = QtGui.QApplication(sys.argv)
ex = Settings()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You can use QpainterPath to draw the arrow and a little math to set the position:
class DemoApp(QtGui.QMainWindow):
def __init__(self, parent=None):
super(DemoApp, self).__init__()
self._squares = []
n_rows, n_cols = 5, 4
squareLB = 50
self.widget = QtGui.QWidget()
grid= QtGui.QGridLayout(self.widget)
self.v = QtGui.QGraphicsView()
grid.addWidget(self.v)
self.setCentralWidget(self.widget)
width, height = (2 + 2)*squareLB, (3 + 2)*squareLB
self._scene = QtGui.QGraphicsScene(0, 0, max(708, width), height)
self.v.setScene(self._scene)
pen = QtGui.QPen(QtCore.Qt.red, 0.0, QtCore.Qt.DotLine)
p = squareLB if width > 708 else (708.0-2*squareLB)/2.0
for i in range(n_rows):
for j in range(n_cols):
it = self._scene.addRect(QtCore.QRectF(0,0,squareLB,squareLB), pen)
it.setPos(p + j*squareLB, i*squareLB)
self._squares.append(it)
path_x = QtGui.QPainterPath()
path_x.lineTo(squareLB*n_cols/2, 0)
path_x.lineTo(squareLB*n_cols/2 - 0.2*squareLB, -0.2*squareLB)
path_x.lineTo(squareLB*n_cols/2, 0)
path_x.lineTo(squareLB*n_cols/2 - 0.2*squareLB, +0.2*squareLB)
pen = QtGui.QPen("green")
pen.setWidth(2)
item_path = self._scene.addPath(path_x, pen)
item_path.setPos(p, (i+1.2)*squareLB)
mytext1 = self._scene.addText("X")
mytext1.setPos(p + j*squareLB/2, (i+1.2)*squareLB)
path_y = QtGui.QPainterPath()
path_y.lineTo(0, -squareLB*n_rows/2)
path_y.lineTo(-0.2*squareLB, -squareLB*n_rows/2 + 0.2*squareLB)
path_y.lineTo(0, -squareLB*n_rows/2)
path_y.lineTo(+0.2*squareLB, -squareLB*n_rows/2 + 0.2*squareLB)
pen = QtGui.QPen("red")
pen.setWidth(2)
item_path = self._scene.addPath(path_y, pen)
item_path.setPos(p - 0.2*squareLB, (i+1)*squareLB)
mytext1 = self._scene.addText("Y")
mytext1.setPos(p - 0.7*squareLB, (i+1)*squareLB/2)

matplotlib legend at the bottom of the figure with twinx

I am trying to draw a legend under two plots (created using twinx). I want the legend to draw at the bottom center aligned with 4 columns. So far no success. How can I make the legend with respect to the entire plot, not just with a single axis object. Any help ?
import matplotlib.pyplot as plt;
import numpy as np;
from matplotlib import rc;
filename = 'ml.pdf';
fig, ax1 = plt.subplots(frameon=False);
rc('mathtext', default='regular');
rc('lines',lw=2.6);
rc('lines',mew=2.4);
rc('text', usetex=True);
x = np.array([5,10,20,50]);
dp_g = np.array([23.43, 29.93, 36.50, 46.07]);
mr_g = np.array([25.33, 31.83, 38.39, 47.75]);
md_g = np.array([24.94, 31.33, 37.80, 47.10]);
sb_g = np.array([27.01, 34.86, 43.18, 54.35]);
lns1 = ax1.plot(x,dp_g,'bs:', label="MD\n($\lambda$=.8)");
lns2 = ax1.plot(x,mr_g,'bs--',label="MR\n($\lambda$=.1)");
lns3 = ax1.plot(x,md_g,'bs-.',label='MD');
lns4 = ax1.plot(x,sb_g,'bs-',label="SB\n($\gamma$=.1)");
ax1.set_ylabel('CG ($\times$ 100)',color='b',size=14);
ax1.set_ylim([20,57]);
ax1.set_xlim([4,51]);
ax1.set_xticks(x);
ax1.tick_params(axis='y', which=u'both', length=0, labelsize=14, colors='b');
ax1.tick_params(axis='x', which=u'both', length=0, labelsize=14);
ax2 = ax1.twinx();
dp_d = np.array([18.84, 19.55, 20.09, 20.08]);
mr_d = np.array([19.42, 19.73, 20.06, 20.04]);
md_d = np.array([19.02, 19.75, 20.28, 20.29]);
sb_d = np.array([20.81, 19.77, 19.20, 19.03]);
lns6 = ax2.plot(x,dp_d,'rv:',label="MD\n($\lambda$=.8)");
lns7 = ax2.plot(x,mr_d,'rv--',label="MR\n($\lambda$=.1)");
lns8 = ax2.plot(x,md_d,'rv-.',label='MD');
lns9 = ax2.plot(x,sb_d,'rv-',label="SB\n($\gamma$=.1)");
lns = lns1 + lns2 + lns3 + lns4 + lns6 + lns7 + lns8 + lns9;
labs = [l.get_label() for l in lns];
ax2.set_ylabel('LD ($\times$ 100)',color='r',size=14);
ax2.set_ylim([15,23]);
ax2.set_xlim([4,51]);
ax2.set_xticks(x);
ax2.tick_params(axis='y', which=u'both', length=0, labelsize=14, colors='r');
ax2.tick_params(axis='x', which=u'both', length=0, labelsize=14);
ax1.set_xlabel('\# of items',size=14);
borderaxespad=2.5, ncol = 1, fontsize='11.5');
lgd = ax1.legend(lns, labs, bbox_to_anchor=(1.01,1.0), loc='lower center', borderaxespad=2.5, ncol = 4, fontsize='14');
fig.savefig(filename,format='pdf',transparent=True, bbox_extra_artists=(lgd,), bbox_inches='tight');
Apart from the broken line borderaxespad=2.5, ncol = 1, fontsize='11.5');, I believe what you want to do is to just remove the bbox_to_anchor=(1.01, 1.0) from the legend-definition. Doing so will put the legend at the bottom center of the plot (however the legend is very wide so it will span the entire width of the plot).

graphical user interface for real time chatbox

I'm trying to create a chat box, using tkinter, for real time chatting. But there is a problem in the GUI part (below) where I am getting this error:
NameError: global name 'action' is not defined
My code:
from Tkinter import *
from PIL import ImageTk,Image
class LoginFrame(Frame):
def action(event):
global EntryBox
global ChatLog
EntryBox.config(state=NORMAL)
EntryText = (EntryBox.get("0.0",END))
LoadMyEntry(ChatLog,EntryText)
EntryBox.delete("0.0",END)
def __init__(self, parent):
Frame.__init__(self, parent,background=("lavender blush"))
self.parent = parent
self.parent.title("Lets Gossip")
self.pack(fill=BOTH, expand=1)
w = 400
h = 500
sw = self.parent.winfo_screenwidth()
sh = self.parent.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2
self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
ChatLog = Text(self, bd=0, bg="white", height="8", width="50", font="Arial",)
scrollbar = Scrollbar(self, command=ChatLog.yview, cursor="heart")
ChatLog['yscrollcommand'] = scrollbar.set
EntryBox = Text(self, bd=0, bg="white",width="29", height="5", font="Arial")
EntryBox.bind("<Return>",action)
EntryBox.bind("<KeyRelease-Return>")
scrollbar1 = Scrollbar(self, command=ChatLog.yview, cursor="heart")
EntryBox['yscrollcommand'] = scrollbar1.set
scrollbar.place(x=376,y=6, height=386)
ChatLog.place(x=6,y=6, height=386, width=370)
scrollbar1.place(x=376,y=401, height=90)
EntryBox.place(x=6, y=401, height=90, width=370)
self.pack()
root = Tk()
lf = LoginFrame(root)
root.mainloop()