You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过按钮将Tkinter的ScrolledText内容传递到其他函数并解决未定义报错

问题根源

有两个核心错误导致报错和功能异常:

  • 作用域问题:KonuIcerik 是KonuOlusturButtonu函数内部的局部变量,Finish函数默认无法访问该变量
  • 按钮回调绑定错误:command = Finish()写法会在按钮定义时就立刻执行Finish函数,而非点击按钮时触发,正确写法应该是只传函数名,或者用lambda包装带参的函数
  • 额外注意:ScrolledText组件的get方法需要传入起止索引参数,直接调用get()也会触发参数错误

修复后代码

def KonuOlusturButtonu():
    window3= Toplevel(root)
    window3.geometry(f'{root_width}x{root_height}+{center_x}+{center_y}')
    window3.title("Konu Oluştur")
    window3.resizable(False, False)
    window3.configure(background='#0a0a0a')

    # Create ScrolledText widget
    KonuIcerik = ScrolledText(window3, width=96,  height=30)
    KonuIcerik.place(relx=0.5, rely=0.55, anchor=CENTER)

    # Create Button widget 修改点:用lambda包装回调,把ScrolledText组件作为参数传入Finish
    button_konubitir = Button(window3, text ="Bitir ve Yayınla", command = lambda: Finish(KonuIcerik))
    button_konubitir.config( height = 2, width = 30 )
    button_konubitir.place(relx=0.5, rely=0.92, anchor=CENTER)

# 修改点:给Finish函数加参数接收传入的ScrolledText组件
def Finish(konu_icerik_widget):
    # 获取全部内容传入"1.0"(第一行第0个字符)到END(文本末尾)的索引范围
    KonuIcerikText = konu_icerik_widget.get("1.0", END)
    print(KonuIcerikText)

内容的提问来源于stack exchange,提问作者ats

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 19:45:09